Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
883 views
in Technique[技术] by (71.8m points)

django - Class Based Views VS Function Based Views

I always use FBVs (Function Based Views) when creating a django app because it's very easy to handle. But most developers said that it's better to use CBVs (Class Based Views) and use only FBVs if it is complicated views that would be a pain to implement with CBVs.

Why? What are the advantages of using CBVs?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The single most significant advantage is inheritance. On a large project it's likely that you will have lots of similar views. Rather than write the same code again and again, you can simply have your views inherit from a base view.

Also django ships with a collection of generic view classes that can be used to do some of the most common tasks. For example the DetailView class is used to pass a single object from one of your models, render it with a template and return the http response. You can plug it straight into your url conf..

url(r'^author/(?P<pk>d+)/$', DetailView.as_view(model=Author)),

Or you could extend it with custom functionality

class SpecialDetailView(DetailView):
    model = Author
    def get_context_data(self, *args, **kwargs):
        context = super(SpecialDetailView, self).get_context_data(*args, **kwargs)
        context['books'] = Book.objects.filter(popular=True)
        return context

Now your template will be passed a collection of book objects for rendering.

A nice place to start with this is having a good read of the docs (Django 3.2+).

Update

ccbv.co.uk has comprehensive and easy to use information about the class based views you already have available to you.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.6k users

...