2 回答

TA貢獻1880條經驗 獲得超4個贊
所以在面向對象編程中,對象是類的實例。所以模型實例和模型對象是一樣的。
讓我們為此做一個例子:
# 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
至于你關于表單的問題,Django 中的每個表單可能包含也可能不包含一個實例。此實例是表單修改的對象。當您創建一個空表單時,這form.instance是None,因為您的表單未綁定到對象。但是,如果您構建一個表單,將要修改的對象作為其參數或填充后,則該對象就是實例。
例子:
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條經驗 獲得超3個贊
CommentForm
是ModelForm
并且ModelForm
具有instance
屬性(您可以設置(更新場景)或 __init__
方法CommentForm
將實例化您設置為的模型的新模型實例Metaclass
來自BaseModelForm來源:
if instance is None:
# if we didn't get an instance, instantiate a new one
self.instance = opts.model()
object_data = {}
添加回答
舉報