Python DRF PrimaryKeyRelatedField使用uuid而不是PK

2024-10-06 09:24:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个Django REST框架API。 我的模型有默认的Django PK供内部使用,uuid字段用于外部引用。在

class BaseModel(models.Model):
    uuid = models.UUIDField(default=uuid.uuid4, editable=False)

class Event(BaseModel):
    title = models.TextField()
    location = models.ForeignKey('Location', null=True, on_delete=models.SET_NULL)

class Location(BaseModel):
    latitude  = models.FloatField()
    longitude = models.FloatField()

我的序列化程序:

^{pr2}$

这很好,这是我检索事件时得到的信息:

{
    "uuid": "ef33db27-e98b-4c26-8817-9784dfd546c6",
    "title": "UCI Worldcup #1 Salzburg",
    "location": 1 # Note here I have the PK, not UUID
}

但我想要的是:

{
    "uuid": "ef33db27-e98b-4c26-8817-9784dfd546c6",
    "title": "UCI Worldcup #1 Salzburg",
    "location": "2454abe7-7cde-4bcb-bf6d-aaff91c107bf" # I want UUID here
}

当然,我希望这种行为对我所有的外国公司和许多领域都有效。 有没有办法为嵌套模型定制DRF使用的字段? 谢谢!在


Tags: django模型uuidtitlemodelslocationclassbasemodel
2条回答

对于嵌套模型字段,您可以在如下序列化程序中使用source参数

class EventSerializer(BaseSerializer):
    location = serializers.CharField(source='location.uuid')

    class Meta:
        model = Event
        lookup_field = 'uuid'  # This does not work
        fields = BaseSerializer.default_fields + ('title', 'location',)

我的一个朋友给我寄来这个解决方案: 它适用于我所有的相关对象。在

from rest_framework import serializers                                                                
from rest_framework.relations import SlugRelatedField                 

class UuidRelatedField(SlugRelatedField):                                                             
    def __init__(self, slug_field=None, **kwargs):                                                    
        slug_field = 'uuid'
        super().__init__(slug_field, **kwargs)                                                        


class BaseSerializer(serializers.ModelSerializer):                                                    
    default_fields = ('uuid',)                                                                        
    serializer_related_field = UuidRelatedField

    class Meta:                                                                                       
        pass

相关问题 更多 >