简体   繁体   中英

How to make queryset in django?

item_list = Item.objects. filter(location_id=location_id)

image_list = Image.objects.filter(?????)

class Image(models.Model):
    item = models.ForeignKey(Item, models.on_delete=CASCADE)

I want to get only those images which item_id in the first queryset item_list

You can make use of the __in lookup [Django-doc] :

image_list = Image.objects.filter()

for some databases, like MySQL that are sometimes not good in optimizing subqueries that have are not dynamic, it might be better to first materialize the list of Item s, and then thus pass a list of ids in Django:

image_list = Image.objects.filter(item__in=item_list)

This is specified in the documentation as:

Be cautious about using nested queries and understand your database server's performance characteristics (if in doubt, benchmark!). Some database backends, most notably MySQL, don't optimize nested queries very well. It is more efficient, in those cases, to extract a list of values and then pass that into the second query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM