查找只有一个特定相关模型的模型

时间:2019-03-05 13:43:22

标签: django django-models many-to-many django-orm

请考虑以下模型:

class Product(models.Model):
    name = models.CharField(max_length=...)

class Size(models.Model):
    name = models.CharField(max_length=...)
    products = models.ManyToManyField(Product, through=ProductXSize,
        related_name='sizes', related_query_name='size')

class ProductXSize(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE,
        related_name='productxsizes', related_query_name='productxsize')
    size = models.ForeignKey(Size, on_delete=models.CASCADE,
        related_name='productxsizes', related_query_name='productxsize')

我想要实现的目标是:

for p in Product.objects.filter(sizes=[Size.object.get(...)]):
    ...

也就是说,找到一种尺寸的产品,并且要有一个特定的尺寸。

1 个答案:

答案 0 :(得分:4)

您需要使用汇总值注释查询集:

https://docs.djangoproject.com/en/2.1/topics/db/aggregation/#filtering-on-annotations

Product.objects.annotate(size_cnt=Count('size'))\  # annotate
    .filter(size_cnt=1)\  # keep all that have only one size
    .filter(size=...).all()  # keep all with a certain size
相关问题