Django:在筛选过程中选择匹配的外键

Django:在筛选过程中选择匹配的外键,django,django-queryset,Django,Django Queryset,我们有下面的示例模型,并且想知道是否可以在同一查询中选择匹配的外键,可能作为注释 class BaseProduct(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=255) sub_title = mo

我们有下面的示例模型,并且想知道是否可以在同一查询中选择匹配的外键,可能作为注释

class BaseProduct(models.Model):
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    name = models.CharField(max_length=255)
    sub_title = models.CharField(max_length=255, blank=True, null=True)
    identifier_retailer = models.CharField(max_length=255)
    tags = models.CharField(max_length=255, blank=True, null=True)
    has_multiple_variants = models.BooleanField(default=False)

class BaseProductVariant(models.Model):
    product = models.ForeignKey(BaseProduct)
    name = models.CharField(max_length=128, blank=True, null=True)
    sub_title = models.CharField(max_length=255, blank=True, null=True)
    date_created = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    description = models.TextField(blank=True, null=True, help_text='Product description')
    features = models.TextField(blank=True, null=True, help_text='One feature per line')
    content = RedactorField(allow_image_upload=True, allow_file_upload=True, blank=True, null=True, help_text='Use this for rich HTML on featured products')
    warranty_string = models.CharField(max_length=255, blank=True, null=True)
    identifier_retailer = models.CharField(max_length=255, blank=True, null=True)
    identifier_upc = models.CharField(max_length=255, blank=True, null=True)
    identifier_model = models.CharField(max_length=255, blank=True, null=True)

我们可以使用
BaseProduct.objects.filter()…
轻松查询结果,但我们希望同时选择匹配的BaseProductVariant的列表,否则我们必须以非常规方式查询数据库,并在
BaseProductVariant.objects.filter上加入python与
prefetch\u相关的
(product\u in=[])。预回迁相关(product)
选择相关的
也适用于此,但由于每行上都有额外的反序列化,速度稍慢。

您可以使用
预回迁相关的
基本产品
预回迁具有相关名称的变体。您也可以使用
预回迁
[1]来自
django.db.models
的对象,以控制预取变量结束时的属性名称:

from django.db.models import Prefetch

products_with_variants = BaseProduct.objects.all().prefetch_related(
    Prefetch('baseproductvariant_set', to_attr='variants'))

for p in products_with_variants:
    print(p.variants)

[1]

你说的“匹配的外键”是什么意思?直接执行
BaseProduct.objects.filter().prefetch_相关(baseproductvariant)
有什么不对?因此,任何人看到这一点,你都可以从Django 1.7开始执行预取(预取)。请参见以下答案: