简体   繁体   中英

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?

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM