Home > Net >  How can I build a query that will return objects that hold more than one specific foreign key?
How can I build a query that will return objects that hold more than one specific foreign key?

Time:09-24

class People(models.Model);
    name = models.CharField()
    surname = models.CharField()

class Votes(models.Model):
    value = models.CharField()
    people = models.ForeignKey(People)

I would like to write a query that will return a queryset of people who have more than one vote(how many foreign keys of Votes has People) . how can I achieve this?

CodePudding user response:

Try this:

from django.db.models import Count

People.objects.annotate(votes_count=Count('votes')).filter(votes_count__gt=1)

votes is a related name here, you can add this in people foreign key in Votes model.

class Votes(models.Model):
    value = models.CharField()
    people = models.ForeignKey(People, related_name='votes')
  • Related