Skip to content
Advertisement

django manytomany field inseting empty data

model

class Enrollee(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id'))
    first_name = models.CharField(max_length=60, verbose_name=_('first name'))
    dependents = models.ManyToManyField(to=Dependant, blank=True, verbose_name=_('dependents'))

class Dependant(TimeStampedModel):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, verbose_name=_('id'))
    first_name = models.CharField(max_length=60, verbose_name=_('first name'))

view

class EnrolleeViewSet(viewsets.ModelViewSet):
    queryset = models.Enrollee.objects.all()
    serializer_class = serializers.EnrolleeSerializer
    filter_class = filters.EnrolleeFilter

serializers

class EnrolleeSerializer(DynamicFieldsMixin, DynamicFieldsModelSerializer):
    dependents = DependantSerializer(many=True, required=False)


    def create(self, validated_data):
        dependant_data = validated_data.pop('dependents')
        enrollee = models.Enrollee.objects.create(**validated_data)
        for dependant in dependant_data:
            models.Dependant.objects.create(**dependant)
        return enrollee

class Meta:
    model = models.Enrollee
    fields = '__all__'

error:

  {
  "first_name": "hmo1",
  "dependents": [],
  }

It means dependents is not inserting

Here I am trying to send nested data for my dependents(ManyToManyField) But, Getting above error while inserting data.

Is there any way we can achive this ?

{
  "first_name":"soubhagya",
  "dependents" : [
     {
       "first_name":"soubhagya"
     }
  ]
}

Above is the data i am sending using post method.

please have a look

Advertisement

Answer

def create(self, validated_data):
    dependant_data = validated_data.pop('dependents')
    enrollee = models.Enrollee.objects.create(**validated_data)
    for dependant in dependant_data:
        obj = models.Dependant.objects.create(**dependant)
        enrollee.dependents.add(obj)
    enrollee.save()
    return enrollee
Advertisement