diogenes
diogenes

Reputation: 2119

Django Query Get all User Items from my Accounts

I am trying to figure out the best (simplest) ways to call all the "Items" from my different User "Accounts."

The Account has the User ForeignKey.

class Acct ( models.Model ):
    user = models.ForeignKey ( settings.AUTH_USER_MODEL)

The Item has the Account foreignKey.

class Items ( models.Model ):
    acct = models.ForeignKey ( Acct )

So when I have a list of Acct's - what is the best way to get all the User's Items for the different accounts?

I can get all the Accounts with something like this:

a = request.user.acct_set.all ().filter ( active = 1 )

Now what is the next call to get the Items for those Accounts?

Only thing I can figure out is to add the User foreignKey to the Items also. (I would also have to add the Active field.)

I hope this makes sense. Thank you.

Upvotes: 0

Views: 642

Answers (2)

solarissmoke
solarissmoke

Reputation: 31404

You don't need to add any more foreign keys - you can just traverse the existing relationships directly in one query like so:

# Fetch all the items associated with all accounts for this user
items = Item.objects.filter(acct__active=1, acct__user=request.user)

Upvotes: 2

diogenes
diogenes

Reputation: 2119

Not sure this is most efficient method, but it seems to be working.

id = request.user.acct_set.values_list ( 'id', flat=True ).filter ( active = 1 )

items = Item.objects.filter ( acct__in = id ) .order_by ( 'date' )

If there is a better way I would appreciate knowing it.

Thanks.

Upvotes: 0

Related Questions