【发布时间】:2015-11-01 14:01:01
【问题描述】:
我在 Django 中基于函数的视图方面拥有不错的经验,现在我正在尝试使用基于类的视图。虽然我能够解决问题,但我不确定标准,我的意思是如果我做的对或错,你们(Django 开发人员)遵循什么。
关于问题的更多细节在这里-
views.py
from django.views.generic import View
class InvoiceTransaction(View):
def __init__(self):
super(InvoiceTransaction, self).__init__()
@method_decorator(csrf_exempt)
def dispatch(self, *args, **kwargs):
return super(InvoiceTransaction, self).dispatch(*args, **kwargs)
def get(self, request, *args, **kwargs):
invoiceid = kwargs.get('invoiceid')
# here I have invoiceid, which is I'm passing through url paramaeters(see urls.py file)
# based on invoice, I can decide what type of GET requests it is
# whether user is asking for a single resource or all resource, right?
if invoiceid:
invoice = [Invoice.objects.get(id=invoiceid)]
else:
invoice = Invoice.objects.all()
def post(self, request, *args, **kwargs):
# some stuff
urls.py
from django.conf.urls import patterns, url
from invoice import views
urlpatterns = patterns('',
(r'^invoices/$', views.InvoiceTransaction.as_view()),
(r'^invoices/(?P<invoiceid>.*)/$', views.InvoiceTransaction.as_view()),
)
我按照这个教程https://realpython.com/blog/python/django-rest-framework-class-based-views/
所以我的问题是我在 urls.py 文件中为单个请求创建了两行(urls)以确定 GET 请求的类型。有没有其他或更好的方法来做到这一点。如何使用视图而不创建 2 个 url 创建一个宁静的 api。
PS:请随意建议对上述代码的改进/更改,因为我是这个东西的新手。可能是我错误地使用了 dispatch 方法,或者真的不需要 init 方法,你建议什么。
【问题讨论】:
标签: python django django-views django-urls django-class-based-views