django - 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')
解决方案
您需要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()
推荐阅读
- methods - F# - 调用方法并分配给构造函数中的属性
- python - 从 url 请求中解压缩 zip 文件
- wpf - 是否可以在 WPF 中使用 GMap.Net Windows Form dll?
- html - 有没有办法使用 CSS 用楔形/三角形装饰线端?
- docker - Docker 提交 - 未保存数据库更改
- matlab - 如何防止带有“assertWarning”的 Matlab 测试将警告文本打印到控制台?
- assembly - 汇编比较来自 incloud 文件的变量
- javascript - Reactjs Ant-Design Menu - 更改子菜单外观
- linux - 远程启动 selenium
- perl - dsmod 用户地址选项卡