[Fixed]-Django Rest Framework how to save a model with Related Field based on ID


Django REST Framework provides a PrimaryKeyRelatedField for exactly this use case.

class RecordSerializer(serializers.ModelSerializer):
    activity = serializers.PrimaryKeyRelatedField()
    owner = serializers.CharField(read_only=True, source='owner.username')
    time_start = serializers.DateTimeField(source='now')

    class Meta:
        model = Records
        fields = ("owner", "activity", "time_start")

This will produce output similar to what you are looking for, and it will accept the id of the activity when you want to update it.


The accepted answer was true for DRF v2.x but is no longer for newer (3.x) versions, as it would raise this AssertionError:

AssertionError: Relational field must provide a queryset argument, or set read_only=True.

For newer versions, just add the queryset argument to it:

class RecordSerializer(serializers.ModelSerializer):
    activity = serializers.PrimaryKeyRelatedField(queryset=Activity.objects.all())
    // [...] 

Leave a comment