I am trying to have a client have a 1 to many relationship with emails and phones.
class Client(models.Model):
class Email(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='emails')
email = models.CharField(null=True, blank=True, max_length=50)
class Phone(models.Model):
client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='phones')
phone = models.CharField(null=True, blank=True, max_length=50)
And this is my serializer
class ClientSerializer(serializers.ModelSerializer):
emails = EmailSerializer(required=False, allow_null=True, many=True)
phones = PhoneSerializer(required=False, allow_null=True, many=True)
I cannot pinpoint why the post will not proceed because it keeps saying client is required.
While i got it to work by adding read_only=True, even if i define a def create(self, validated_data) in the ClientSerializer i cannot get hold of the emails and phones array in the json data.
This is how I called the serializer in the views.py
serializer = ClientSerializer(data=request.data)
This is how the json data looks like
{"id":0,"emails":[{"id":0,"emailType":"Home","email":"[email protected]"}],"phones":[],"name":"me"}
So my goal is if in the emails array, if there is an email property, insert it, otherwise ignore. same as phones.
This is how i called the serializer in views.py
@api_view('POST'])
def client(request):
serializer = ClientSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_200_OK)
So inside ClientSerializer, i create the client object via Client.objects.create(validated_data);
Then extracted the emails array from the validated_data and did a for loop. for (ed in emailData):
Created an email = Email() object then
email.email = emailData.get('email')
email.client = client
But it gives me an error "null value in column "client_id" violates not-null constraint". When i do a print(email), the client object from email.client is null which is weird, considering print(client) has an id.
Thoughts?