1

I am new to Django REST, I was trying to make some entry to the DB using the serilaizer in django rest. But i am getting some errors while using the create method.

My models are,

class CoreInformation(models.Model):
        site_name = models.CharField(max_length=145, blank=True, null=True)
        status = models.CharField(max_length=45, blank=True, null=True)
        created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True)

        class Meta:
            managed = False
            db_table = 'core_information'

class CoreDetailInformation(models.Model):
    core_info = models.ForeignKey('CoreInformation', models.DO_NOTHING, related_name='core_base_info')
    old_sac = models.CharField(max_length=45, blank=True, null=True)
    msc = models.CharField(max_length=45, blank=True, null=True)

    class Meta:
        db_table = 'core_detail_information'

And i have two ModelSerializer like below ,

class CoreDetailSerializer(serializers.ModelSerializer):

    class Meta:
        model = CoreDetailInformation
        fields = ('id','old_sac', 'msc')


class CustomCoreInfoSerializer(serializers.ModelSerializer):
    core_base_info = CoreDetailSerializer(many=True)

    class Meta:
        model = CoreInformation
        # fields = '__all__'
        fields = ('id', 'site_name', 'status', 'created_at', 'core_base_info')

        @transaction.atomic
        def create(self, validated_data):
            try:
                with transaction.atomic():
                    base_info = CoreInformation.objects.create(site_name=validated_data['site_name'],status=validated_data['status']                                         
                    for site_detail in validated_data['core_base_info']:
                        CoreDetailInformation.objects.get_or_create(msc=site_detail['msc'],old_sac=site_detail['old_sac'],core_info=base_info)
            except CoreInformation.DoesNotExist as e:
                raise e
            except CoreDetailInformation.DoesNotExist as e:
                raise e

and my views.py is ,

class CoreInformation(generics.ListCreateAPIView):
    queryset = models.CoreInformation.objects.all()
    serializer_class = CustomCoreInfoSerializer

    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        instance = self.perform_create(serializer)
        serializer = self.get_serializer(instance=instance)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

    def perform_create(self, serializer):
        return serializer.create(validated_data=serializer.validated_data)

To create the CoreInformation my input will be like below,

{
    "site_name": "xxxxxxxxxx",
    "status": "create",
    "core_base_info": [{
                "old_sac": '1',
                "msc": "abc1,abc2"
            },
            {
                "old_sac": '2',
                "msc": "abc3,abc4"
            }]
}

But when i am compiling its returns me the below error,

AssertionError at /api/core/
The `.create()` method does not support writable nested fields by default.
Write an explicit `.create()` method for serializer `src.core.serializers.CustomCoreInfoSerializer`, or set `read_only=True` on nested serializer fields.

I found this , but did n't help for me.

Any help would be greatly appreciated. Thanks.

2
  • You can't pass nested json in perform_create to create a new entry. Only pass the id of the foreign key. Commented Mar 1, 2019 at 10:51
  • Looking at your json structure I think the thing which you are trying to do is a ManyToMany Relationship. Commented Mar 1, 2019 at 11:01

1 Answer 1

0

I think that you can use this GitHub to solve your problem Try this: https://github.com/beda-software/drf-writable-nested

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.