[Answered ]-How to get or create on Django Rest Framework and return it

1👍

DRF serializers don’t handle nested serializers so they have to be manually managed. For the case of creating a new model instance, you can override the serializer’s .create() function and do the create manually.

There is .get_or_create() for django models that you can use for creating a new user, if it does not exist.

# serializers.py

from django.db import transaction

class UserSerializer(serializers.SeralizerMethodField):
    class Meta:
        model = User
        fields = ['first_name', 'last_name', 'email', 'phone']

class UserPostSerializer(serializers.ModelSerializer):
    checkin_date = serializers.DateField(format="%Y-%m-%d")
    checkout_date = serializers.DateField(format="%Y-%m-%d")
    guest_number = serializers.IntegerField(min_value=0)
    user = UserSerializer()

    class Meta:
        model = UserPost
        fields = ['checkin_date', 'checkout_date', 'guest_number', 'user']

    @transaction.atomic
    def create(self, validated_data):
        user_data = validated_data.pop('user', {})
        user_email = user_data.pop('email', '')

        user, created = User.objects.get_or_create(email=user_email, defaults=user_data)

        validated_data['user_id'] = user.id
        return super().create(validated_data)

The code above is simply based on the response json data expected.

👤Kyell

Leave a comment