使用 ManytoManyField 的 Django 查询

Django query using 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 提前致谢。

关注

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