[Django]-Python django rest framework. How to serialize foreign key UUID in some specific format?

7👍

if you want to be able to specify the for_key then you can’t use @Withnail’s answer because the for_key there is read_only.
You should use a PrimaryKeyRelatedField.

  class BSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(format='hex')
    for_key = serializers.PrimaryKeyRelatedField(queryset=A.objects.all())

    class Meta:
        model = B
        fields = ('id', 'desc', 'for_key')

2👍

When you serialize across a relationship in DRF, you just need to call the serializer in the second model.

class ASerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(format='hex')
    class Meta:
        model = A
        fields = ('id', 'desc')

class BSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(format='hex')
    for_key = ASerializer(many=True, read_only=True)
    class Meta:
        model = B
        fields = ('id', 'desc', 'for_key')

2👍

What you are looking for is :

class BSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(format='hex')
    for_key = serializers.UUIDField(format='hex', source='for_key.id')
    class Meta:
      model = B
      fields = ('id', 'desc', 'for_key')

Leave a comment