仅在提供方法时才覆盖它的方法

时间:2019-05-07 15:29:08

标签: django python-2.7 django-models

我已重写save方法以从其他模型的字段继承。但是,我只想在创建对象时不传递该字段的值的情况下继承。如果在创建对象时传递了值,则我不希望它继承。

我有两个模型:

Product具有字段type(外键)和should_remove

Type具有字段nameshould_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)

1 个答案:

答案 0 :(得分:0)

尝试以下

def save(self, *args, **kwargs):
    # How do I access the passed should_remove here??
    should_remove = kwargs.get("should_remove")
    # . . .