使用创建时间django多对多字段过滤器

时间:2016-03-08 14:47:59

标签: python django many-to-many

我有一个名为ClassRoom的模型,

class ClassRoom(model.Model):
    class_name = models.CharField(max_lenth=100)
    students = models.ManyToManyField(User)

view.py就像这样。

def addstudents(request):
    class_room = ClassRoom.objects.get(id=1)
    class_name.students.add(request.user)

我将这些学生添加到ClassRoom。 我想列出今天加入课堂的所有学生。 如何通过 their joining time 过滤此学生?

当我们使用django ManyToManyField时,django会在数据库中创建一个额外的表。在该表中包含created时间。我可以使用此字段进行过滤吗?

1 个答案:

答案 0 :(得分:1)

您可以使用自定义表格(docs here)将额外字段添加到M2M关系表。

class ClassRoom(models.Model):
    class_name = models.CharField(max_length=100)
    students = models.ManyToManyField(User, through='ClassMate')


class ClassMate(models.Model):
    class_room = models.ForeignKey(ClassRoom, on_delete=models.CASCADE)
    user = model.ForeignKey(User, on_delete=models.CASCADE)
    date_joined = models.DateField(auto_now_add=True)

然后你可以这样做:

class_room = ClassRoom.objects.get(...)

class_room.students.filter(date_joined=datetime.today())

请记住(正如文档所说)现在您必须实例ClassMate个对象来添加关系:

class_room = ClassRoom.objects.get(...)
user = request.user
class_mate = ClassMate(class_room=class_room, user=user)
class_mate.save()