我有一个人模型,其字段为first_name,last_name和email。我想将这些字段发送到一个视图,该视图将检查数据库中的现有实例。如果有,则返回ID,否则将创建新实例并返回新ID。使用标准FBV我会这样做(减少版本,减去验证等):
from django.http import HttpResponse
from mysite.models import Person
import json
def get_or_create_person(request):
try:
person = Person.objects.get(first_name=request.POST['first_name'],
last_name=request.POST['last_name'], email=request.POST['email'])
except Person.DoesNotExist:
person = Person(first_name=request.POST['first_name'],
last_name=request.POST['last_name'], email=request.POST['email'])
person.save()
response = {'id': person.id}
return HttpResponse(json.dumps(response))
将它转换为使用CBV并将其与其余框架联系起来是否有任何实际意义?如果是这样,我将如何去做呢?我希望它作为CBV的主要原因是我可以使用我已经包含在我的应用程序的其他部分中的mixins等。
编辑:我考虑过使用通过其余框架提供的ViewSets,但他们将此功能拆分为GET和POST方法,获取检索记录并发布更新或创建记录。我基本上需要一个可以接受的视图。
答案 0 :(得分:1)
我必须将get和post功能结合起来如下:
class GetOrCreateCustomerView(APIView):
'''
API endpoint that takes an email address, first name & surname and then
either returns the matching customer id or creates a new customer and
returns that id
'''
required_fields = ('first_name', 'last_name', 'email')
def get(self, request, format=None):
request_data = request.GET
response = self.get_customer_id(request_data)
return JSONResponse(response)
def post(self, request, format=None):
request_data = request.POST
response = self.get_customer_id(request_data)
return JSONResponse(response)
def get_customer_id(self, data):
kwargs = {}
for f in self.required_fields:
if f in data:
kwargs[f] = data[f]
else:
return None
try:
customer = Customer.objects.get(**kwargs)
except Customer.DoesNotExist:
customer = Customer(**kwargs)
customer.save()
if customer.id is not None:
response = {'customer_id': customer.id}
else:
response = {
'error': 'Please provide a first name, surname and email address'
}
return response
此处引用的JSONResponse是rest framework docs中的JSONResponse。
答案 1 :(得分:0)
对于django-rest-framework中基于类的视图,这通常通过以下方式完成:
我相信django rest框架文档中有几个例子