2

How do I use django's queryset to get a list of users from the MyUser table where transaction_paid is False in my UserBankTransaction table?

class UserBankTransaction(models.Model):
    user = models.ForeignKey(MyUser)
    plaid_transaction_id = models.CharField(max_length=300, unique=True)
    charge_amount = models.DecimalField(max_digits=10, decimal_places=2)
    account_id = models.CharField(max_length=300)
    location_name = models.CharField(blank=True, max_length=300)
    roundup_amount = models.DecimalField(max_digits=10, decimal_places=2, null=True)
    transaction_date = models.DateField()
    transaction_paid = models.BooleanField(default=False)
    created_date = models.DateTimeField(auto_now=False, auto_now_add=True)


class MyUser(AbstractBaseUser):
    username = models.CharField(max_length=255,unique=True,)
    email = models.EmailField(verbose_name='email address',max_length=255,unique=True)
    first_name = models.CharField(max_length=120,null=True,blank=True,)
    last_name = models.CharField(max_length=120,null=True, blank=True,)
    created = models.DateTimeField(auto_now_add=True, null=True, blank=True)
    updated = models.DateTimeField(auto_now=True, null=True, blank=True)

2 Answers2

5

Querying with backward relationship will do:

MyUser.objects.filter(userbanktransaction_set__transaction_paid=False)
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • Im getting the following error - `FieldError: Cannot resolve keyword 'userbanktransaction_set' into field. Choices are: created, email, first_name, id, is_active, is_admin, is_member, last_login, last_name, logentry, password, payment, paymentdata, pledge, updated, useralert, userbanktransaction, userchapter, userfinance, username, userprofile, userschool` – Brandon Mitchell Aug 28 '18 at 01:48
  • 1
    It seems that the default reverse lookup name does not have a `_set` suffix as I remembered. Try instead: `MyUser.objects.filter(userbanktransaction__transaction_paid=False)` – blhsing Aug 28 '18 at 01:50
  • and what would be the best way if i want to filter the transactions by date, for example, only those that happened in the past 10 days ? – Gers Feb 25 '20 at 14:00
  • i know i can filter the transactions first, then retrieve the list of user IDs, and from that querying the MyUser model, but i'm curious to know if there's another wat – Gers Feb 25 '20 at 15:46
4

If you are going to retrieve a list of user IDs:

UserBankTransaction.objects \
    .filter(transaction_paid=False)\
    .values_list('user', flat=True)

If you are going to retrieve a list of user objects:

MyUser.objects.filter(userbanktransaction_set__transaction_paid=False)

or your can specify a related_name in UserBankTransaction.user:

class UserBankTransaction(models.Model):
    user = models.ForeignKey(MyUser, related_name='bank_transactions') 

then you can simply do this:

MyUser.objects.filter(bank_transactions__transaction_paid=False)
Tsang-Yi Shen
  • 532
  • 3
  • 15