亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

區分對象與實例

區分對象與實例

泛舟湖上清波郎朗 2023-01-04 15:33:20
有些人認為模型是一個對象,有些人認為是一個實例。誰能告訴我這兩個例子有什么區別?model.py:class ToDo(models.Model):    name = models.CharField(max_length=100)    due_date = models.DateField()    def __str__(self):        return self.nameforms.py:class ToDoForm(forms.ModelForm):    class Meta:        model = ToDo        fields = ['name', 'due_date']views.py:def todo_list(request):    todos = ToDo.objects.all()    context = {'todo_list': todos}    return render(request, 'todoApp/todo_list.html', context)考慮下面的代碼,什么是表單實例?class PostDetailView(DetailView):    model = Post    def post(self, *args, **kwargs):        form = CommentForm(self.request.POST)        if form.is_valid():            post = self.get_object()            comment = form.instance            comment.user = self.request.user            comment.post = post            comment.save()            return redirect('detail', slug=post.slug)        return redirect('detail', slug=self.get_object().slug)
查看完整描述

2 回答

?
慕村225694

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

我希望它更清楚一點。


查看完整回答
反對 回復 2023-01-04
?
蠱毒傳說

TA貢獻1895條經驗 獲得超3個贊

CommentFormModelForm并且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 = {}


查看完整回答
反對 回復 2023-01-04
  • 2 回答
  • 0 關注
  • 128 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號