![](/img/trans.png)
[英]How to get objects if user is in a field of another django model's many-to-many field?
[英]Django - get the last object of a model with many objects
我有两个模型。 父亲和儿子的模特。 子模型中的关系为:
father = models.ForeignKey(Father, related_name="father")
现在在真实数据库中,我有5个父亲,每个父亲有5个儿子。 我想找到20岁的儿子。
father = Father.objects.all()
#how to find all sons with age 20?
您的标题与您的问题不太匹配,并且您的问题缺少信息。 但是,这是您想要的吗?
fathers = Fathers.objects.all()
sons = Son.objects.filter(father__in=fathers, age=20)
但是,假设所有儿子都有父亲,您可以这样写:
sons = Son.objects.filter(age=20)
如果您正在寻找一个父亲的所有20岁儿子:
father = Fathers.objects.get(id=101)
sons = Son.objects.filter(father=father, age=20)
假设您为父子拥有一个不同的模型(这不是一个好的设计决策,但这是我从您的问题中得出的结论)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.