0

I have 2 models:

class Parameter(models.Model):
    name = models.CharField('Название', max_length=50)


class ProductParameter(models.Model):
    product = models.ForeignKey(Product, on_delete=models.CASCADE, verbose_name='Продукт', related_name='parameters')
    parameter = models.ForeignKey(
        'Parameter',
        on_delete=models.CASCADE,
        verbose_name='Параметр',
        related_name='product_parameters'
    )

I do the queryset for getting all parameters that has more than 1 ProductParameter:

parameters = Parameter.objects.annotate(
    count=Count('product_parameters')
).exclude(count__lte=1)

But that's not working. When a parameter obj has 2 ProductParameter objects, the count equals to 1.
When I use the expression below, all works:

parameters = [param for param in Parameter.objects.all() if param.product_parameters.count() > 1]

Where is my error?

1 Answer 1

1

Maybe using count as the field name is the issue. Try renaming it or omitting it to use the defaulted field name.

parameters = Parameter.objects.annotate(Count('product_parameters')
).exclude(product_parameters__count__lte=1)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.