4
votes

I want to create a caretaker. This is my model:

class Caretaker(models.Model):
    user = models.OneToOneField(User)
    language = models.ForeignKey('Translation', blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_('language'))
    patients = models.ManyToManyField('Patient', through='CaretakerPatient')
    specialists = models.ManyToManyField('Caretaker', through='CaretakerSpecialist')
    name = models.CharField(_('name'), max_length=50)
    email = models.CharField(_('e-mail'), max_length=100)
    time_zone = models.CharField(_('time zone'), max_length=50)
    is_primary = models.BooleanField(default=False)
    active = models.BooleanField(default=True)

As you see there is a relation oneTOone with django.contrib.auth.models.User.

My API view is the following

@csrf_exempt
@api_view(['POST'])
@renderer_classes((CustomJSONRenderer,))
def create_user(request):
    serializer = CaretakerSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=201)
    return Response(serializer.errors, status=400)

My Serializer classes...

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User

class CaretakerSerializer(serializers.ModelSerializer):
    user = UserSerializer()
    language = serializers.SlugRelatedField(slug_field='language_code', read_only=True)
    time_zone = serializers.StringRelatedField()

    class Meta:
        model = Caretaker
        fields = ('id', 'user', 'language', 'name', 'email', 'time_zone', 'active')

    def create(self, validated_data):
        print validated_data
        user = User(
            email=validated_data['email'],
            username=validated_data['username']
        )
        user.set_password(validated_data['password'])
        user.save()
        caretaker = Caretaker.objects.create(**validated_data)
        return caretaker

My question is: sending data like:

{'username': 'xxx', 'password': 'xxx', 'email': '[email protected]', 'name': 'John Smith' ... }

How can I split username and password in order to create first the user, and then use this object to create the caretaker? The validated_data just gave me the fields of the caretaker model.

2

2 Answers

4
votes

As you are using a nested user serializer you should send the data like this:

{"user": {"username": "xxx", "password": "xxx", ...},
 "language": "...",
 ...
} 

Then you have a user item in validated_data and can create a user instance:

def create(self, validated_data):
    user_data = validated_data.pop('user')
    user = User(
        email=user_data['email'],
        username=user_data['username']
    )
    user.set_password(user_data['password'])
    user.save()
    caretaker = Caretaker.objects.create(**validated_data)
    return caretaker
1
votes

Don't forget to pass the User instance to the create()method of your Caretaker model to get the correct relations inside your db:

def create(self, validated_data):
    user_data = validated_data.pop('user')
    user = User.objects.create(**user_data)
    # pass the newly created user instance here
    caretaker = Caretaker.objects.create(user=user, **validated_data)
    return caretaker    

Since your fields inside the JSON are named corresponding to your model, you can reduce your lines of code.