简体   繁体   English

Django 用对象查询集注释字段

[英]Django annotate field with queryset of objects

Suppose I have two models:假设我有两个模型:

ModelA and ModelB模型A和模型B

How can I annotate a queryset of ModelB with objects from ModelA?如何使用 ModelA 中的对象注释 ModelB 的查询集?

queryset = ModelB.objects.filter(...).annotate(models_a=Subquery(ModelA.objects.filter(...)))

In order to have queryset.models_a as a Queryset of objects ModelA.为了将queryset.models_a作为对象 ModelA 的查询集。

Thanks you all!谢谢大家!

EDIT:编辑:

This are my models:这是我的模型:

class Allergen(models.Model):
    name = models.CharField(_('Allergen name'), max_length=20, choices=ALLERGENS,
                            help_text=_('Product allergen. Example: gluten'), unique=True)

    def __str__(self):
        return self.name

    class Meta:
        ordering = ['name']


class Product(models.Model):
    name = models.CharField(_('Name'), max_length=255, help_text=_('Product name'))
    supplier = models.ForeignKey(Supplier, blank=True, null=True, related_name='supplier_products',
                                 on_delete=models.CASCADE)
    allergens = models.ManyToManyField(Allergen, blank=True, related_name='product_allergens')
    unit = models.CharField(_('Unit'), max_length=20, choices=UNITS, default='g')
    price = models.FloatField(_('Sale price'), default=0)
    unit_price = models.FloatField(_('Unit price'))

    class Meta:
        ordering = ['name', ]
        indexes = [models.Index(fields=['name', 'supplier']), ]


class Recipe(models.Model):
    sections = models.ManyToManyField(Section, related_name='recipes', blank=True)
    title = models.CharField(_('Recipe title'), max_length=255, help_text=_('Recipe. Example: american chicken salad'),
                             blank=True)
    unit = models.CharField(_('Unit'), max_length=20, choices=UNITS)
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='user_recipes')

    class Meta:
        ordering = ['title']
        indexes = [models.Index(fields=['title'])]


class IngredientRecipe(models.Model):
    name = models.CharField(_('Name'), max_length=255)
    recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE, related_name='ingredients')
    products = models.ManyToManyField(Product, related_name='ingredient_products')
    quantity = models.FloatField(_('Quantity'))

    class Meta:
        ordering = ['-id']
        unique_together = ('name', 'recipe')
        indexes = [models.Index(fields=['name', 'recipe'])]

I'm trying to include the allergens related with the recipe.我试图包括与食谱相关的过敏原。

If you are working with just one recipe, you can just add a model property that returns the related allergens of the recipe by using the reverse relations like this:如果你只使用一个食谱,你可以只添加一个 model 属性,通过使用像这样的反向关系返回食谱的相关过敏原:

class Recipe(models.Model):
    ...

    @property  # or consider using cached_property
    def allergens(self):
        return Allergen.objects.filter(
            product_allergens__ingredient_products__recipe=self,
        )

Then you can access the allergens through the instance:然后你可以通过实例访问过敏原:

recipe = Recipe.objects.first()
print(recipe.allergens)

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

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