如何为 ManyToMany 记录添加时间戳

How to add a timestamp to a ManyToMany record

我有以下型号:

class Meeting(models.Model):
    meeting_title = models.CharField(default='', max_length=128, blank=True, null=True)
    meeting_time = models.TimeField(blank=False, null=False)
    meeting_date = models.DateField(blank=False, null=False) 
    meeting_visitors = models.ManyToManyField(Visitor, blank=True, default="")

以及以下形式:

class AddMeetingForm(forms.ModelForm):
    class Meta:
            model = Meeting
            fields = '__all__'

由于meeting_visitors是一个ManyToMany字段,它可以包含一个或多个Visitor记录。

此表单可以在一天中的不同时间更新。我想知道添加到会议中的每个 Visitor 的时间戳(即在现实世界中,他们到达会议的时间)。

最简单/最有效的方法是什么?

我知道我可以获得 timestamp 模型实例是通过 meeting_updated = models.DateTimeField(auto_now_add =False, auto_now=True) 更新的,但我想要 meeting_visitors 字段中每条记录的等效项。

您可以在多对多字段中使用 through 关键字轻松创建此关系

Django allows you to specify the model that will be used to govern the many-to-many relationship. You can then put extra fields on the intermediate model. The intermediate model is associated with the ManyToManyField using the through argument to point to the model that will act as an intermediary.

因此,您可以这样使用它。

class Visitor(models.Model):
    name = models.CharField(max_length=30)

class Meeting(model.Model):
    title = models.CharField(max_length=30)
    time = models.TimeField(blank=False, null=False)
    date = models.DateField(blank=False, null=False) 
    attendance = models.ManyToManyField(Visitor, through='Attendant')


class Attendant(models.Model):
    visitors = models.ForeignKey(Visitor)
    meeting = models.ForeignKey(Meeting)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)