我已重写save方法以从其他模型的字段继承。但是,我只想在创建对象时不传递该字段的值的情况下继承。如果在创建对象时传递了值,则我不希望它继承。
我有两个模型:
Product
具有字段type
(外键)和should_remove
Type
具有字段name
和should_remove
当我创建新产品条目而未传递should_remove
时,它将自动从正确的Type
继承。
type = Type.objects.create(name="open", should_remove=False)
product = Product.objects.create(type=type)
product.should_remove # False
但是,如果我传递了should_remove
字段,它仍然继承自Type
type = Type.objects.create(name="open", should_remove=False)
product = Product.objects.create(type=type, should_remove=True)
product.should_remove # False
我的想法是在should_remove
方法内访问传递的save()
的值,并仅在传递时设置它。如何在save方法中访问传递的值?
def save(self, *args, **kwargs):
# How do I access the passed should_remove here??
if not self.id:
self.should_remove = self.type.should_remove
super(Product, self).save(*args, **kwargs)
答案 0 :(得分:0)
尝试以下
def save(self, *args, **kwargs):
# How do I access the passed should_remove here??
should_remove = kwargs.get("should_remove")
# . . .