使用ManytoManyField

时间:2019-02-19 17:12:45

标签: django django-models foreign-keys manytomanyfield

使用示例代码:

from django.db import models

class Person(models.Model):
    name = models.CharField(max_length=128)

    def __str__(self):
        return self.name

class Group(models.Model):
    name = models.CharField(max_length=128)
    members = models.ManyToManyField(Person, through='Membership')

    def __str__(self):
        return self.name

class Membership(models.Model):
    person = models.ForeignKey(Person, on_delete=models.CASCADE)
    group = models.ForeignKey(Group, on_delete=models.CASCADE)
    date_joined = models.DateField()

如何通过date_joined获得最近5个人的姓名及其所属团体的名字顺序?像这样:

"name1" "group1" "19/02/2019"
"name2" "group1" "19/02/2019"
"name1" "group2" "19/02/2019"
"name3" "group1" "18/02/2019"
"name4" "group2" "17/02/2019"

我尝试了很多选择,但我无法完成:S预先感谢。

1 个答案:

答案 0 :(得分:1)

您可以按照

Membership.objects.values('person__name', 'group__name', 'date_joined').order_by(date_joined)[:5]