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.