simakazi
simakazi

Reputation: 53

django-rest-framework: serializer.save doesn't return object's id

Short description: I have a problem with ModelSerializer. It is not filling id field of object on save.

Useful details. My model:

class Platform(models.Model):
    identifier = models.CharField(max_length=32, unique=True)
    description = models.TextField()

My serializer:

class PlatformSerializer(serializers.ModelSerializer):
    identifier = serializers.CharField(required=True, max_length=32)
    description = serializers.CharField(max_length=100000, required=False)

    class Meta:
        model=Platform
        fields=('id', 'identifier', 'description',)
        read_only_fields=('id',)

And APIView:

class PlatformView(APIView):
    def post(self, request, id_platform=None, format=None):
        serializer = PlatformSerializer(data=request.DATA)
        if serializer.is_valid():            
            serializer.save()            
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        else:
            return Response(form_error(u"Ошибка при создании КА: ", serializer.errors), status=status.HTTP_400_BAD_REQUEST)

The line serializer.save() returns Platform object with id==None. Is it a bug or am I missing something?

Upvotes: 1

Views: 5495

Answers (2)

simakazi
simakazi

Reputation: 53

Ouch. I'm sorry for this question. Somebody created pk field for this table as integer with default value from sequence (without owning this sequence). Django performs pk selection as SELECT CURRVAL(pg_get_serial_sequence('tablename','id')). But pg_get_serial_sequence returns Null. I don't know why django-rest-framework doesn't performselect ... returning id;`. I'll try to fix the database.

Upvotes: 1

Toan Nguyen
Toan Nguyen

Reputation: 661

I think this serializer class should work:

class PlatformSerializer(serializers.ModelSerializer):
    class Meta:
        model=Platform

ModelSerializer:

By default, all the model fields on the class will be mapped to corresponding serializer fields.

Upvotes: 1

Related Questions