Reputation: 1201
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
Reputation: 476503
You can retrieve the Company
s 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 django-3.2, 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