gpt4 book ai didi

Django Rest API : How to get rid of 'UUID' in json when serializing models?

转载 作者:行者123 更新时间:2023-12-04 23:38:43 25 4
gpt4 key购买 nike

为什么 'UUID' 出现在 'profile' 键的值前面,如何正确删除它?

名册/serializers.py

class ShiftSerializer(serializers.ModelSerializer):

class Meta:
model = Shift
fields = ('id', 'profile', 'location', 'date', 'start_time', 'end_time')

配置文件/模型.py
class Profile(models.Models):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)

名册/models.py
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True)
profile = models.ForeignKey('profiles.Profile', null=True, blank=True)

python manage.py shell
from roster.models import Shift
from roster.serializers import ShiftSerializer

myshift = Shift.objects.first()
serializer = ShiftSerializer(myshift)
serializer.data

输出:
{'id': '92ca258e-8624-434a-b61d-e1cd3b80e0e8', 'profile': UUID('0081b028-0a11-47fb-971e-c47177ed93be')

最佳答案

您可以重写 representation ,像这样

class ShiftSerializer(serializers.ModelSerializer):
class Meta:
model = Shift
fields = '__all__'

def to_representation(self, obj):
return {
"id": obj.id,
"profile": obj.profile.id,
"location": obj.location,
"date": obj.date,
"start_time": obj.start_time,
}

关于Django Rest API : How to get rid of 'UUID' in json when serializing models?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46111680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com