尽管有用,但Django的ManyToManyField具有很高的优势,它可以在删除时杀死所有涉及的主体……其内部的ForeignKey on_delete = CASCADE。为什么要硬编码?!覆盖此行为的简单方法是什么?
考虑了多种解决方案后,似乎最干净的方法是从外部处理delete信号调用并在值上设置null ...是否有更简洁的方法?而且它不应该成为ManyToManyField上的危险信号吗?
代码:
class Feed(models.Model):
source = models.ForeignKey('Source', null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
url = models.CharField(max_length=512)
def __str__(self):
return f'{self.source.brand} - {self.title}'
class FeedList(models.Model):
name = models.CharField(max_length=255, unique=True, null=False)
feeds = models.ManyToManyField(Feed, blank=True)
尝试删除FeedList会触发与其关联的Feed对象的删除,这是我想避免的。
尝试通过自定义ManyToManyField,我做了以下事情:
class Feed(models.Model):
source = models.ForeignKey('Source', null=True, on_delete=models.CASCADE)
title = models.CharField(max_length=255)
url = models.CharField(max_length=512)
def __str__(self):
return f'{self.source.brand} - {self.title}'
class FeedToFeedList(models.Model):
feed = models.ForeignKey('Feed', on_delete=models.DO_NOTHING)
feed_list = models.ForeignKey('FeedList', on_delete=models.DO_NOTHING)
class FeedList(models.Model):
name = models.CharField(max_length=255, unique=True, null=False)
feeds = models.ManyToManyField(Feed, blank=True, through='FeedToFeedList')
现在,当尝试执行搜索/删除操作时,我会遇到各种奇怪的错误...稍后会更新有关他们的问题...