lord stock
lord stock

Reputation: 1201

Django perform Annotate , count and Compare

I have following Model.

class Gallery(BaseModel):
    company = models.ForeignKey(to=Company, on_delete=models.CASCADE)
    image = models.ImageField(
        upload_to=upload_company_image_to,
        validators=[validate_image]
    )

    def __str__(self):
        return f'{self.company.name}'

    

I want to allow maximum upto 5 image to be uploaded by one company so I tried my query as

def clean(self):
    print(Gallery.objects.values('company').annotate(Count('image')).count())

I don't know how to compare above query with Integer 5. How do I do that?

Upvotes: 0

Views: 915

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

You can retrieve the Companys that have more than five images with:

from django.db.models import Count

Company.objects.alias(
    num_images=Count('gallery')
).filter(num_images__gt=5)

Prior to , you can work with .annotate(…) [Django-doc]:

from django.db.models import Count

Company.objects.annotate(
    num_images=Count('gallery')
).filter(num_images__gt=5)

Upvotes: 2

Related Questions