2 回答

TA貢獻1880條經(jīng)驗 獲得超4個贊
所以在面向?qū)ο缶幊讨?,對象是類的實例。所以模型實例和模型對象是一樣的?/p>
讓我們?yōu)榇俗鲆粋€例子:
# This is your class
class ToDo(models.Model):
name = models.CharField(max_length=100)
due_date = models.DateField()
# If somewhere I call
my_var = ToDo() # my_var contain an object or an instance of my model ToDo
至于你關(guān)于表單的問題,Django 中的每個表單可能包含也可能不包含一個實例。此實例是表單修改的對象。當您創(chuàng)建一個空表單時,這form.instance是None,因為您的表單未綁定到對象。但是,如果您構(gòu)建一個表單,將要修改的對象作為其參數(shù)或填充后,則該對象就是實例。
例子:
form = CommentForm()
print(form.instance) # This will return None, there is no instance bound to the form
comment = Comment.objects.get(pk=1)
form2 = CommentForm(instance=comment)
print(form2.instance) # Now the instance contain an object Comment or said an other way, an instance of Comment. When you display your form, the fields will be filled with the value of this instance
我希望它更清楚一點。

TA貢獻1895條經(jīng)驗 獲得超3個贊
CommentForm
是ModelForm
并且ModelForm
具有instance
屬性(您可以設(shè)置(更新場景)或 __init__
方法CommentForm
將實例化您設(shè)置為的模型的新模型實例Metaclass
來自BaseModelForm來源:
if instance is None:
# if we didn't get an instance, instantiate a new one
self.instance = opts.model()
object_data = {}
添加回答
舉報