Django ManyToManyField 如何添加 created_at 和 updated_at
Django ManyToManyField how to add created_at and 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')
您需要使用名为 though
的参数覆盖 ManyToManyField
。
更多信息 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',
<b>through='GroupProfileRelationship'</b>)
class Profile (models.Model):
# fields
下面是直通模型
<b>class GroupProfileRelationship(models.Model):</b>
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)
Note that some options will no longer available. such as add()
remove()
Really important to take a look at the official documentation here
如何将 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')
您需要使用名为 though
的参数覆盖 ManyToManyField
。
更多信息 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',
<b>through='GroupProfileRelationship'</b>)
class Profile (models.Model):
# fields
下面是直通模型
<b>class GroupProfileRelationship(models.Model):</b>
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)
Note that some options will no longer available. such as
add()
remove()
Really important to take a look at the official documentation here