这是我在 django 中的代码,
class Comment(models.Model):
text = models.CharField(max_length=400)
writer = models.ForeignKey(Email, on_delete=models.DO_NOTHING)
replied_to = models.ManyToManyField('self', related_name='replied')
class Meta:
db_table = 'Comment'
当我向reply_to添加评论实例时,它会添加到父级,但reply实例在其reply_to字段中保留指向相关对象的指针。 有没有办法删除指向相关评论的指针而不从父级删除回复实例?
最佳答案
是的,您可以在此处使用 .remove(..)
方法:
mycomment.replied_to<b>.remove(</b>othercomment<b>)</b>
这不会从数据库中删除othercomment
,但它将不再是ManyToManyField<中
.replied_to
的一部分
请注意,默认情况下,ManyToManyField
与 self
的关系是对称。这意味着,如果一条评论位于另一条评论的 replied_to
中,则另一条评论的 replied_to
也包含第一条评论。您可以设置symmetrical=…
parameter [Django-doc]为 False
使其不对称:
class Comment(models.Model):
text = models.CharField(max_length=400)
writer = models.ForeignKey(Email, on_delete=models.DO_NOTHING)
replied_to = models.ManyToManyField('self'<b>, symmetrical=False</b>, related_name='replied')
class Meta:
db_table = 'Comment'
关于python - 从多对多字段中删除,但不从相关模型中删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59635966/