简体   繁体   English

Django Filter Select_Related

[英]Django Filter Select_Related

When using select_related, has anyone developed a way to filter on a field in the foreign key table. 使用select_related时,有没有人开发过一种方法来过滤外键表中的字段。

For example given these models: 例如给出这些模型:

class Author(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=40)

class AuthorExtra(models.Model):
    author = models.ForeignKey(Author)
    type = models.ForeignKey(ExtraType)
    value = models.CharField(max_length = 24)

I would like a way to cache all of the related AuthorExtra objects of a specific type. 我想要一种方法来缓存特定类型的所有相关AuthorExtra对象。

You cannot do this with select_related as it will only work for One-to-One fields or ForeignKeys. 您不能使用select_related执行此操作,因为它仅适用于一对一字段或ForeignKeys。 For reverse relationships like this, the development version has introduced prefetch_related which is exactly what you're looking for. 对于像这样的反向关系,开发版本引入了prefetch_related ,这正是您正在寻找的。

https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related https://docs.djangoproject.com/en/dev/ref/models/querysets/#prefetch-related

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

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