Django api保存到数据库(没有REST框架工作)

时间:2017-07-13 09:27:53

标签: python django api django-rest-framework

如何使用Django但没有rest-framework执行以下任务? 例如,如何将用户保存到我的模型中? 这是我目前的代码:

串行

from rest_framework import serializers
from .models import User,Blog

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('std_num','password' , 'first_name',  'last_name', 'email') 

的观点

from rest_framework.views import  APIView
from rest_framework.response import  Response
from rest_framework import  status
from .models import User
from .serializers import UserSerializer

class register (APIView):
    def post(self, request):

        serializer = UserSerializer(data = request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=111)
        return Response(serializer.errors, status=100)

2 个答案:

答案 0 :(得分:0)

import json
from .models import User
from django.http import HttpResponse
from django.views import View

class register(View):
    def post(self, request):
        if not request.POST.get('password') or not request.POST.get('email'):
            #Do checking for other values 
            return_dict = {'status':False,'code':111}
        else:
           user_obj =User.objects.create(email=request.POST.get('email'),
                                  password=request.POST.get('password'))
           #save the needed values 
           user_obj.save()
           return_dict = {'status':True,'code':100}
        return HttpResponse(json.dumps(return_dict))

检查api响应中的“代码”或“状态”值以执行相关操作

答案 1 :(得分:0)

您无需显式创建用户对象。此作业通过调用 serializer.save()完成。您自己创建用户效率很低。 Django 提供内置功能,但如果您愿意,可以覆盖它。