如何向我的ManyToManyField添加created_at和updated_at字段?
class Profile (models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Group(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
profiles = models.ManyToManyField(Profile, related_name='groups')
答案 0 :(得分:2)
您需要使用名为ManyToManyField
的参数覆盖though
。
更多信息here
class Group(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
profiles = models.ManyToManyField(Profile, related_name='groups',
through='GroupProfileRelationship')
class Profile (models.Model):
# fields
现在是直通模型
class GroupProfileRelationship(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
请注意,某些选项将不再可用。例如
add()
remove()
看看正式文档here
非常重要