How to make `ModelSerializer` in `DRF` to don't ignore `id` field

I have a problem in nested ModelSerialzier in DRF.

My code

class ModelA(models.Model):
    name = models.CharField(max_length=50)

class ModelB(models.Model):
    some = models.CharField(max_length=50, blank=True, null=True)
    model_a = models.ForeignKey(ModelA, on_delete=models.CASCADE)

class CreateModelA(GenericAPIView):
    serializer_class = ModelASeri

    def post(self, request):
        serializer = ModelASeri(

        if serializer.is_valid():
            return Response({"status": "OK"}) 

        return Response({"status": "error", "error": serializer.errors})

class ModelBSeri(serializers.ModelSerializer):
    class Meta:
        model = ModelB
        fields = ("id", "some")

class ModelASeri(serializers.ModelSerializer):
    model_b = ModelBSeri(many=True, required=False)
    class Meta:
        model = ModelA
        fields = ("__all__")

    def create(self, validated_data):
        model_b = validated_data.pop("model_b", None)
        model_a = super().create(validated_data)


        if model_b:
            for model in model_b:
                obj = ModelB.objects.get(model["id"])
                obj.model_a = model_a

        return model_a

My problem is when I try to access model["id"], I get KeyError.

The print function will give me this:

[OrderedDict([('some', None)])]

the id field is ignored here

What I try to do is I want to have a view that creates ModelA and relate the needed fields that are related to created ModelA instance.

My input Example:

    "name": "test name",
    "model_b": [
        "id": 1
        "id": 2

Here I want to create a ModelA with name=test name and relate ModelB instances with ids: [1, 2] to the ModelA created instance.

Back to Top