Django ORM deduplication counter

class Country(models.Model):
    name = models.CharField(max_length=255)


class City(models.Model):
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    name = models.CharField(max_length=255)


class Score(models.Model):
    city = models.ForeignKey(City, on_delete=models.CASCADE)

I need the deduplicated count of city.country in the score model.

canada = Country.objects.create(name="Canada")
USA = Country.objects.crerate(name="USA")

ottawa = City.objects.create(name="Ottawa", country=cannada)
washington = City.objects.create(name="Washington", country=usd)
new_york =  City.objects.create(name="New York", country=usd)

Score.objects.create(city=ottawa)
Score.objects.create(city=ottawa)
Score.objects.create(city=washington)
Score.objects.create(city=new_york)

I want Canada 1 point US 2 points like this.

city = City.objects.annotate(point= ???)

ottawa city[0].point ==> 1

washington city[1].point ==> 2

new_york city[2].point ==> 2

Back to Top