我有一个模型UserProfile
,它有一个与Django用户模型相关的OneToOneField
我在views.py中有UserProfileList
class UserProfileList(generics.ListCreateAPIView):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
我想将数据发布到UserProfileList
格式如:
{ "username":"username",
"email":"email@email",
"password":"password",
"secret_id":1
}
('用户名','电子邮件','密码'来自User
型号
secret_id来自UserProfile
)
它可以在User
和UserProfile
表格中保存数据
是posibble?
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User)
secret_id=models.IntegerField(default=0)
views.py
from rest_framework import generics
from django.contrib.auth.models import User
from .serializers import UserProfileSerializer, UserSerializer
from account.models import UserProfile
class UserList(generics.ListCreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
class UserProfileList(generics.ListCreateAPIView):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
class UserProfileDetail(generics.RetrieveUpdateDestroyAPIView):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
serializer.py
from django.contrib.auth.models import User
from rest_framework import serializers
from account.models import UserProfile
class UserProfileSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = UserProfile
fields = ('user','secret_id')
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('username','email','password')
答案 0 :(得分:0)
是的,有可能实现这一目标。
为了能够访问username
中的email
,password
和UserProfileSerializer
字段,您需要在其上定义这些字段,否则,序列化程序的字段验证将抛出未在序列化程序中定义的字段:
class UserProfileSerializer(serializers.HyperLinkedModelSerializer):
email = serializers.CharField(write_only=True)
username = serializers.CharField(write_only=True)
password = serializers.CharField(write_only=True)
class Meta:
...
请注意,明确定义的字段为write_only
,因此在阅读时它们不会显示。
上述代码将确保您不会在序列化程序的validated_attrs
和.create()
方法中从.update()
中删除这些字段。
在此之后你有2个选项
您需要覆盖.create()
的{{1}}方法,以便在UserProfileSerializer
模型之外创建User
模型。
UserProfile
您可以在class UserProfileSerializer(serializers.HyperLinkedModelSerializer):
# above definitions
def create(self, validated_attrs):
# now you have here the email, username and password arguments
email = validated_attrs.pop('email', None)
username = validated_attrs.pop('username', None)
password = validated_attrs.pop('password', None)
# your creation logic here
user = User.objects.create(...)
user_profile = UserProfile.objects.create(user=user, ...)
创建过程中处理UserProfile
的创建(请参阅handling saving related instances in model manager classes)。为此,您需要定义自定义User
类。
UserManager