如何将数据从Serializer保存到模型数据库。以下是代码但不保存数据到数据库的示例!
例如我正在使用示例示例视图:
的 views.py
@api_view(['GET', 'POST', ])
def login(request):
if request.method == "POST":
s = LoginSerializer(data=request.data)
if s.is_valid():
s.save()
return Response(s.data, status=201)
else:
return Response(s.data, status=203)
else:
return Response("", status=404)
models.py
from django.db.models import Model
from django.db import models
class UserDetails(Model):
userid = models.AutoField(primary_key=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
phone = models.CharField(max_length=15)
class UserLogin(Model):
userid = models.ForeignKey(UserDetails, on_delete=None)
email = models.CharField(max_length=20)
password = models.CharField(max_length=30)
的 serializers.py
from rest_framework import serializers
from api.models import UserLogin, UserDetails
class LoginSerializer(serializers.Serializer):
userid = serializers.Field()
email = serializers.EmailField()
password = serializers.CharField(max_length=20)
def create(self, validated_data):
return UserLogin.objects.create(**validated_data)
答案 0 :(得分:0)
serializers.py
from rest_framework import serializers
from api.models import UserLogin, UserDetails
class LoginSerializer(serializers.Serializer):
userid = serializers.Field()
email = serializers.EmailField()
password = serializers.CharField(max_length=20)
def create(self, validated_data):
return super().create(validated_data)