x-yuri
x-yuri

Reputation: 18863

Find models that have only one particular related model

Consider the following models:

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')

What I'd like to achieve is along the lines of:

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

That is, find products that have one size, and a particular one at that.

Upvotes: 1

Views: 49

Answers (1)

Risadinha
Risadinha

Reputation: 16666

You need to annotate the queryset with an aggregated value:

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

Upvotes: 4

Related Questions