简体   繁体   English

如何在 Django 中创建查询集?

[英]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我只想获取第一个查询集 item_list 中 item_id 的那些图像

You can make use of the __in lookup [Django-doc] :您可以使用__in查找[Django-doc]

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

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:对于某些数据库,例如 MySQL,有时不擅长优化非动态子查询,最好先实现Item列表,然后在 Django 中传递 id 列表:

image_list = Image.objects.filter(item__in=list(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.一些数据库后端,尤其是 MySQL,不能很好地优化嵌套查询。 It is more efficient, in those cases, to extract a list of values and then pass that into the second query.在这些情况下,提取值列表然后将其传递到第二个查询中会更有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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