猿问

区分对象与实例

有些人认为模型是一个对象,有些人认为是一个实例。谁能告诉我这两个例子有什么区别?


model.py:


class ToDo(models.Model):

    name = models.CharField(max_length=100)

    due_date = models.DateField()


    def __str__(self):

        return self.name

forms.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)


泛舟湖上清波郎朗
浏览 163回答 2
2回答

慕村225694

所以在面向对象编程中,对象是类的实例。所以模型实例和模型对象是一样的。让我们为此做一个例子:# This is your classclass ToDo(models.Model):    name = models.CharField(max_length=100)    due_date = models.DateField()# If somewhere I callmy_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 formcomment = 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我希望它更清楚一点。

蛊毒传说

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 = {}
随时随地看视频慕课网APP

相关分类

Python
我要回答