0

So I have queryset1 that filters ModelA by 2 parameters:

queryset1 = ModelA.objects.all().filter(par1="X",par2="Y")

Then I have another queryset2 that I would like to filter ModelB by grabbing the elements that have already been filtered by queryset1, and also that follow another parameter:

queryset2 = ModelB.objects.all().filter(par3="X" for i in queryset,par4="Z")

My question is: Is there a way to perform a queryset on a queryset that you have already made? In the end I would like to pull the objects from ModelA and ModelB that follow par1 par2 par3. How would I do this?

5
  • 1
    I don't understand what are you trying to do, can you show us your model? What's the relationship between ModelA and ModelB? What are you trying to do with for i in queryset? Commented Jul 29, 2016 at 20:15
  • ModelA and ModelB have some of the same objects, but some different objects. I want to grab the objects that are the same in both models, then do a filter on those objects. Commented Jul 29, 2016 at 20:18
  • please post examples of models so it is a little more clear Commented Jul 29, 2016 at 20:24
  • 2
    Oh that's what you are doing? No, in django you can't filter on 2 models. Queryset needs to be objects from one model only. Commented Jul 29, 2016 at 20:29
  • Post your model code Commented Jul 29, 2016 at 20:30

2 Answers 2

1

it's quite possible to achieve without a for loop. The disadvantage of using a for loop is that you are actually executing two queries and retrieving the results for the first one. If that happens to produce a large number of rows you are burning up resources and slowing down the response time.

queryset2 = ModelB.objects.all().filter(par3__in=queryset,par4="Z")

This would result in a subquery as explained at https://docs.djangoproject.com/en/1.9/ref/models/querysets/

You can also use a queryset to dynamically evaluate the list of values instead of providing a list of literal values:

SELECT * FROM app_modelb where par3 IN (SELECT ...)
Sign up to request clarification or add additional context in comments.

Comments

1

What you can do is:

  1. When par3 is a relation of the same type of the queryset1:

    queryset2 = ModelB.objects.all().filter(par3__in=queryset1, par4="Z")
    
  2. Use the values_list('some_field', flat=True) notation, when part3 is not a relation

    queryset2 = ModelB.objects.all().filter(par3__in=queryset1.values_list('X', flat=True), par4="Z")
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.