将 request.data 映射到 onetoone 字段

mapping request.data into a onetoone field

我有一个 JSON 请求数据如下,我想使用 Django 序列化程序和视图处理该数据,以便使用 POST 请求在数据库中创建记录。

{
    "username":"user1",
    "first_name":"name1",
    "email":"name1@gmail.com",
    "phone": "123456",
    "app_id": "435673339303abc"

}

以下是我的 Django 数据库模型和序列化程序,其中创建了一个自定义用户模型,其中包含一个 onetoone Django 用户模型:

models.py

from django.contrib.auth.models import User
from django.db import models


class CustomUserModel(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    phone = models.CharField(max_length=20, blank=True)
    app_id = models.CharField(max_length=20, blank=True)

serializers.py

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


class CustomUserSerializer(serializers.ModelSerializer):
    user = UserSerializer(required=True)

    class Meta:
        model = CustomUserModel
        fields = ('user', 'phone', 'app_id')

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = UserSerializer.create(UserSerializer(), validated_data=user_data)
        customuser, created = CustomUserModel.objects.update_or_create(user=user, defaults={
            'phone': validated_data.pop('phone'),
            'app_id': validated_data.pop('app_id')})
        return customuser

views.py

class usersApi(generics.ListAPIView):
    serializer_class = CustomUserSerializer

    def get_queryset(self):
        queryset = CustomUserModel.objects.all()
        return queryset

    def post(self, request, format=None):
        serializer = CustomUserSerializer(data=request.data)
        if serializer.is_valid(raise_exception=ValueError):
            serializer.create(validated_data=request.data)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.error_messages,
                        status=status.HTTP_400_BAD_REQUEST)

但是使用这个序列化程序和视图,我必须如下传递一个嵌套的 json 数据和我不想传递的用户对象。

{
    "user":
    {
    "username":"user1",
    "first_name":"name1",
    "email":"name1@gmail.com"
    },
    "phone": "123456",
    "app_id": "435673339303abc"
}

您可以从视图中的 CustomUserModel 获取行。 CustomUserModel.objects.get(用户=request.user.user_id)

经过多次迭代,我找到了一种通过将请求数据映射到字典中来实现这一点的方法。 views.py

class usersApi(generics.ListAPIView):
    serializer_class = CustomUserSerializer

    def get_queryset(self):
        queryset = CustomUserModel.objects.all()
        return queryset

    def post(self, request, format=None):
        username = request.data['username']
        first_name = request.data['first_name']
        email = request.data['email']
        phone = request.data['phone']
        app_id = request.data['app_id']

        user_data = {'user': {'username': username, 'first_name': first_name, 'email': email}, 'phone': phone,
                     'app_id': app_id}
        serializer = CustomUserSerializer(data=user_data)

        if serializer.is_valid(raise_exception=ValueError):
            serializer.create(validated_data=user_data)
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.error_messages,
                        status=status.HTTP_400_BAD_REQUEST)