python django rest框架。如何以某种特定格式序列化外键UUID?

时间:2018-12-06 10:49:13

标签: python django django-rest-framework

我有两个模型A和B,它们都具有UUID作为主键。 B中有一个与A相关的外键。

class A(models.Model):
    id = models.UUIDField(primary_key=True, editable=False)
    desc = models.CharField(max_length=128, null=True)

class B(models.Model):
    id = models.UUIDField(primary_key=True, editable=False)
    desc = models.CharField(max_length=128, null=True)
    for_key = models.ForeignKey(A, on_delete=models.SET_NULL, null=True)

这是我的序列化器,

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')
    class Meta:
        model = B
        fields = ('id', 'desc', 'for_key')

如您所见,我将uuid(主键)更改为十六进制格式。但是for_key的格式为默认格式(hex_verbose)。 那么如何将模型B中的外键 for_key序列化为 hex 格式?

3 个答案:

答案 0 :(得分:0)

在DRF中的关系上进行序列化时,只需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')

答案 1 :(得分:0)

如果您希望能够指定for_key,那么您将无法使用@Withnail的答案,因为for_key是只读的。 您应该使用synth1 scatter plot

  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 :(得分:0)

您正在寻找的是:

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')