码迷,mamicode.com
首页 > 其他好文 > 详细

django self.instance

时间:2018-02-13 15:41:35      阅读:158      评论:0      收藏:0      [点我收藏+]

标签:const   调用   建议   call   body   field   div   来源   子类   

在stackoverflow上看到一个问题,正好是我疑惑很久的相关问题。

[原问题地址]https://stackoverflow.com/questions/18265023/self-instance-in-django-modelform

What does self.instance in Django ModelForm constructor mean and where can I find a documentation about it?

class MyModelForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyModelForm, self).__init__(*args, **kwargs)
        if self.instance:
        ...

下面有大神回答:

In a ModelForm, self.instance is derived from the model attribute specified in the Meta class. Your self in this context is obviously an instance of your subclass of ModelForm, and self.instance is (and will be on saving the form without errors) an instance of the model class you specified, although you have not done so in your example.

Accessing self.instance in init may not work, though doing so after calling the parent‘s init probably will. Further, I wouldn‘t recommend trying to change the instance directly. If you are interested, have a look at the BaseModelForm code on Github. The instance can also be specified when creating a new form via the instance argument.
This is not a generic Python thing. This is something that‘s defined specifically by ModelForm, in the superclass init

大致意思是:在modelform中,self.instance来源于元类中指定的model属性。你的self明显是这个上下文中ModelForm子类的实例化,而self.instance是(将在没有错误的情况下保存在表单中)你指定的model类的一个实例。尽管你在示例中没有这么做。

直接在__init__中访问self.instance也许不会工作,虽然在调用父类的__init__后可能会生效。此外,我不建议直接更改实例。如果您感兴趣,请查看Github上的BaseModelForm代码。在通过实例参数创建新表单时也可以指定实例。
最后总结下:self.instance不是python中通用的方法,这是以ModelForm形式,在超类的__init__中特别定义的方法。

附录:

在django文档中,Model instance reference这部分提到Model.full_clean(exclude=None, validate_unique=True)。

There are three steps involved in validating a model:

  • 验证模型字段 - Model.clean_fields()
  • 验证模型作为一个整体 - Model.clean()
  • 验证字段唯一性 - Model.validate_unique()

All three steps are performed when you call a model‘s ~Model.full_clean() method。而在我们使用ModelForm时,对 is_valid() 的调用将对表单上包含的所有字段执行这些验证步骤。

django self.instance

标签:const   调用   建议   call   body   field   div   来源   子类   

原文地址:https://www.cnblogs.com/dion-90/p/8446684.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!