Django查询相关记录集,但只有相关表中的max

时间:2017-07-07 21:42:12

标签: python django django-queryset

假设我有两个相关的django模型。属于单个群组的群组和人员。

class Group(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)

class Person(models.Model):
    group = models.ForeignKey('Group', on_delete=models.CASCADE, related_name='group')
    name = models.CharField(max_length=100, null=True, blank=True)
    birthdate = models.DateTimeField(auto_now_add=True)

我想要做的是返回Person对象的查询集,该对象仅由每个组中具有最大生日的人组成。所以如果有5个组'我想要一个5' Person'的查询集。对象,由maxmium birthdate决定。

1 个答案:

答案 0 :(得分:0)

请尝试:

gruop_id = Group.objects.get(name='?').id
Person.objects.filter(group__id=gruop_id).order_by('birthdate').values()[:5]

我可能没有理解你。也许,你想要反过来。

Person.objects.filter(group__id=gruop_id).order_by('birthdate').values().reverse()[:5]
相关问题