成为基于类的视图还是泛型的类基本视图? [英] To be a Class based view or a generic class base view?

查看:81
本文介绍了成为基于类的视图还是泛型的类基本视图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,下面我在观看Django Con EU谈话视频后,通过基于第一类的视图创建了该视频。

So below I have just created by first Class based view after watching a Django Con EU talk video.

它可以正常工作并了解它的作用。 我不了解基于类的视图或基于类的通用视图(我刚刚构建的视图)之间的区别?

It works and understand what it does. I don't understand the difference between a Class based view or a generic class base view - which I have just build?

class GroupListView(ListView):
    """
    List all Groups.
    """
    context_object_name = 'groups'
    template_name = 'contacts/home.html'

    def get_context_data(self, **kwargs):
        """
        Get the context for this view.
        """
        # Call the base implementation first to get a context.
        context = super(GroupListView, self).get_context_data(**kwargs)
        # Add more contexts.
        context['tasks'] = Upload.objects.filter(uploaded_by=self.request.user).order_by('-date_uploaded')[:5]
        context['unsorted'] = Contact.objects.unsorted_contacts(user=self.request.user).count()

        return context

    def get_queryset(self):
        """
        Get the list of items for this view. This must be an iterable, and may
        be a queryset (in which qs-specific behavior will be enabled).
        """
        queryset = Group.objects.for_user(self.request.user)
        return queryset 


推荐答案

Django随附了一组试图解决一些常见问题的视图,例如:

Django comes with a set of views that are trying to solve some common problems, eg:


  • 编辑对象

  • 显示单个对象

  • 显示对象列表

由于这些视图可用于不同的模型,因此被称为通用
Generic在这种情况下与它们的实现方式无关-在较早的Django版本中,函数视图是默认的(视图是函数),现在它们已成为类。

Because these views can be used for different models, they are called generic. "Generic" in this case hasn't anything to do with the way they are implemented - in older Django version function views were the default (the views were functions), now they have became classes.

您的示例视图实际上是基于基于类的视图,它继承自基于基于类的通用视图

Your example view is actually a class-based view that inherits from a class-based generic view.

这篇关于成为基于类的视图还是泛型的类基本视图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆