dingoj
dingoj

Reputation: 11

ModelChoiceField: get only objects used as a Foreign Key in another object

I have two classes:

class Nationality(Model):
    name = models.Charfield()

class Person(Model):
    name = models.Charfield()
    nationality = ForeignKey("Nationality")

I want to display, in a ModelChoiceField in an altogether different form, only those nationalities that are used as a foreign key in the Person table. There are actually many more, but I'm only interested in those that are used as a foreign key to an existing Person.

This doesn't work, as it returns a dict with the fieldname and referenced primary key.

Person.objects.values('nationality')

I want the Nationality object to be returned so I am able to reference its name attribute.

I don't want to use raw SQL, as my model's further complicated by a multilingual module.

Upvotes: 0

Views: 405

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599610

You can use annotations to filter those nationalities that have at least one Person.

from django.db.models import Count
Nationality.objects.annotate(person_count=Count('person')).filter(person_count__gte=1)

Upvotes: 2

Related Questions