Django REST Framework - PrimaryKeyRelatedField


DRF tip:

To represent the target of the relationship with its primary key, you can use PrimaryKeyRelatedField in the serializer.

👇

# serializer:
class TagSerializer(serializers.ModelSerializer):
    posts = serializers.PrimaryKeyRelatedField(many=True, read_only=True)

    class Meta:
        model = Tag
        fields = ['name', 'posts']

# result:
{
    "name": "Stories",
    "posts": [
        1,
        2
    ]
}