简体   繁体   中英

How to combine two different Models in serializers module (Django)?

I want to create a Registration API, wherein, I aim to combine the User Model and Profile Model in order to create a new user by adding the username, email, password (User Model fields) and gender, salary, company, and address (Profile Model fields). I attempted to use the source from this link . However, I am not able to POST any data in. This is my code so far:

views.py:

class RegisterAPIView(APIView):
    def post(self, request, format=None):
        serializer = ProfileSerializer(data=request.data)
        if serializer.is_valid():
             serializer.save()
             return Response("Thank you for registering", status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

serializers.py:

from rest_framework import serializers
from users.models import Profile
from django.contrib.auth.models import User

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ['gender', 'company', 'salary', 'address']

class RegisterBSerializer(serializers.ModelSerializer):   #User Model serializer
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ['username', 'email', 'password']

    def create(self, validated_data):
        profile_data = validated_data.pop('profile')
        password = validated_data.pop('password', None)
        user = User.objects.create(**validated_data)
        if password is not None:
            user.set_password(password)
        user.save() 
        Profile.objects.create(user = user, **profile_data)
        return user

Can anyone hint me on where I am going off-track?.

I am not able to add data via DRF: image

Usually, I should be getting a Body which states:

{"username" : "this field is required",
"email" : "this field is required",
"password" : "this field is required", (will be hashed using set_password())
"gender" : "this field is required",} etc etc...

You can do this by writing custom to_representation method like this

class RegisterBSerializer(serializers.ModelSerializer):   #User Model serializer
    profile = ProfileSerializer()

    class Meta:
        model = User
        fields = ['username', 'email', 'password']

    def to_representation(self, instance):
        data = super().to_representation(instance)
        profile = data.pop('profile', {})
        data.update(profile)
        return data

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM