gpt4 book ai didi

Django 外键 on_delete : how to pass argument to callable when using models. SET

转载 作者:行者123 更新时间:2023-12-02 00:52:14 25 4
gpt4 key购买 nike

这是我的 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)
)

当我删除“图像”时,它与“项目”调用 set_image 相关,这会返回错误,因为 models.SET 不会将实例传递给可调用对象。我怎样才能改变这种行为?我应该覆盖 models.SET 还是有其他方法可以解决它?

最佳答案

重写 Image 删除方法以删除 ItemforeignKey

以下内容可以用作中间模型基类,将此功能添加到您的所有模型中:

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()

source

关于Django 外键 on_delete : how to pass argument to callable when using models. SET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22465127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com