这是我的models.py:
def set_image(instance):
return Image.objects.filter(user=instance.user)[0]
class User(models.Model):
user = models.CharField(max_length=50)
class Image(models.Model):
user = models.ForeignKey(User)
image = models.ImageField(upload_to='media')
class Item(models.Model):
user = models.ForeignKey(User)
image = models.ForeignKey(
Image,
blank=True,
null=True,
on_delete=models.SET(set_image)
)
当我删除'Image'时,它的相关'Item'调用set_image,它返回一个错误,因为models.SET没有将实例传递给callable。我该如何改变这种行为?我应该覆盖models.SET还是有其他方法吗?
答案 0 :(得分:1)
覆盖Image delete方法以删除Item ForeignKey
以下内容可用作中间模型基类,以将此功能添加到您的所有模型中:
from django.db import models
class Model(models.Model):
"""
Intermediate model base class.
"""
class Meta:
abstract = True
def delete(self, *args, **kwargs):
self.clear_nullable_related()
super(Model, self).delete(*args, **kwargs)
def clear_nullable_related(self):
"""
Recursively clears any nullable foreign key fields on related objects.
Django is hard-wired for cascading deletes, which is very dangerous for
us. This simulates ON DELETE SET NULL behavior manually.
"""
for related in self._meta.get_all_related_objects():
accessor = related.get_accessor_name()
related_set = getattr(self, accessor)
if related.field.null:
related_set.clear()
else:
for related_object in related_set.all():
related_object.clear_nullable_related()