Django queryset distinct foreign key and count


What we want to do here is:
1. We want distinct foreign key from the records
2. We want this unique foreign key contains number of records that belongs to.

Example:
Country -> has many -> Insurance

1
2
3
4
5
Country(models.Model):
    name = models.Charfields(..)

Insurance(model.Model):
    country = models.ForeignKey(Country)

We want to distinct Country in Insurance and show numbers of insurance in each unique Country.

1
Insurance.objects.order_by("country").values_list("country__name").distinct().annotate(Count("id"))

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.