Django ManyToManyField如何添加created_at和Updated_at

时间:2018-06-27 20:41:08

标签: django django-models django-orm

如何向我的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')

1 个答案:

答案 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

非常重要