Shard
Shard

Reputation: 3245

Using data from django queries in the same view

I might have missed somthing while searching through the documentation - I can't seem to find a way to use data from one query to form another query.

My query is:

sites_list = Site.objects.filter(worker=worker)

I'm trying to do something like this:

for site in sites_list:
    [Insert Query Here]

Edit: I saw the awnser and im not sure how i didnt get that, maybe thats the sign im up too late coding :S

Upvotes: 1

Views: 113

Answers (2)

James Bennett
James Bennett

Reputation: 11163

You can also use the __in lookup type. For example, if you had an Entry model with a relation to Site, you could write:

Entry.objects.filter(site__in=Site.objects.filter(...some conditions...))

This will end up doing one query in the DB (the filter condition on sites would be turned into a subquery in the WHERE clause).

Upvotes: 0

Dan Lorenc
Dan Lorenc

Reputation: 5394

You could easily do something like this:

sites_list = Site.objects.filter(worker=worker)

for site in sites_list:
    new_sites_list = Site.objects.filter(name=site.name).filter(something else)

Upvotes: 2

Related Questions