Reputation: 468
I am trying to create a "Prospect" object, which is nested under my "Appointment" serializer. But when posting, I keep getting the error "NOT NULL constraint failed: schedule_appointment.prospect_id".
I suppose Django is expecting me to pass a prospect_id when posting, but how do I go about doing this? I've read elsewhere that an alternative is to set the foreign key to null=True, but in my case, an Appointment MUST have a Prospect.
Any suggestions?
Serializers
class ProspectSerializer(serializers.ModelSerializer):
class Meta:
model = Prospect
fields = [ 'id','first_name', 'last_name', 'email']
class AppointmentSerializer(serializers.ModelSerializer):
prospect = ProspectSerializer()
class Meta:
model = Appointment
fields = ['appointment_time', 'unit', 'staff', 'prospect']
def create(self, validated_data):
prospect_data = validated_data.pop('prospect')
appointment = Appointment.objects.create(**validated_data)
Prospect.objects.create(appointment=appointment, **prospect_data)
return appointment
Models
class Appointment(models.Model):
appointment_time = models.DateTimeField()
unit = models.ForeignKey(Unit, on_delete=models.CASCADE)
staff = models.ForeignKey(Staff, on_delete=models.CASCADE)
prospect = models.ForeignKey(Prospect, on_delete=models.CASCADE)
class Prospect(models.Model):
first_name = models.CharField(max_length=50)
last_name = models.CharField(max_length=50)
email = models.EmailField(max_length=30)
Upvotes: 0
Views: 178
Reputation: 659
First you need create Prospect model and then Appointment
def create(self, validated_data):
prospect_data = validated_data.pop('prospect')
prospect = Prospect.objects.create(**prospect_data)
appointment = Appointment.objects.create(prospect=prospect, **validated_data)
return appointment
Upvotes: 2