doniyor
doniyor

Reputation: 37856

Django - get the last object of a model with many objects

I have two models. A father and a son model. And the relationship in the son model is:

father = models.ForeignKey(Father, related_name="father")

Now in the real database, I have 5 fathers, each father has 5 sons. I want to find sons with age 20.

father = Father.objects.all()
#how to find all sons with age 20?

Upvotes: 1

Views: 216

Answers (1)

Joe
Joe

Reputation: 47609

Your title doesn't quite match your question and your question is missing information. But, is this what you want?

fathers = Fathers.objects.all()
sons = Son.objects.filter(father__in=fathers, age=20)

but, assuming all Sons have Fathers, you could just write this as

sons = Son.objects.filter(age=20)

If you are looking for all sons age 20 from one father:

father = Fathers.objects.get(id=101)
sons = Son.objects.filter(father=father, age=20)

This assumes that you have a different model for Father and Son (which is not a good design decision but it is what I understand from your question).

Upvotes: 1

Related Questions