首页 > 解决方案 > Django ManyToManyField 如何添加 created_at 和 updated_at

问题描述

如何将 created_at 和 updated_at 字段添加到我的 ManyToManyField?

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')

标签: djangodjango-modelsdjango-orm

解决方案


您需要ManyToManyField使用名为 的参数覆盖though
更多信息在这里

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()

看看这里的官方文档真的很重要


推荐阅读