Brandon Mitchell
Brandon Mitchell

Reputation: 185

Get List of related objects - Django Queryset

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)

Upvotes: 2

Views: 5307

Answers (2)

Tsang-Yi Shen
Tsang-Yi Shen

Reputation: 542

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)

Upvotes: 4

blhsing
blhsing

Reputation: 107095

Querying with backward relationship will do:

MyUser.objects.filter(userbanktransaction_set__transaction_paid=False)

Upvotes: 5

Related Questions