首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >UUID在rest-framework中显示为整数

UUID在rest-framework中显示为整数
EN

Stack Overflow用户
提问于 2021-03-12 13:24:38
回答 1查看 51关注 0票数 0

这是我的modelserializer和'admin`‘

代码语言:javascript
运行
复制
class UserData(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    pub_date = models.DateTimeField('date published',default=timezone.now)   

class UserDataSerializer(serializers.ModelSerializer):
    class Meta:
        model = Genre
        fields = ('id','pub_date')
    def create(self, validated_data):
        user_data = UserData()
        user_data.save()
        return user_data

class UserDataAdmin(admin.ModelAdmin):
    list_display = ["id","pub_date"]
    search_fields = ['id']

在管理屏幕中,id字段如下所示

但在rest-framework中,id显示为整数。

我该怎么解决这个问题??

感谢您的@periwinkle评论

我变了

代码语言:javascript
运行
复制
class UserDataSerializer(serializers.ModelSerializer):
    id = serializers.UUIDField(format='hex_verbose') // add this
    class Meta:
        model = Genre
        fields = ('id','pub_date')
    def create(self, validated_data):
        user_data = UserData()
        user_data.save()
    return user_data

在此之后,当POST url创建新的数据。

它显示错误

代码语言:javascript
运行
复制
HTTP 400 Bad Request
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

{
    "id": [
        "This field is required."
    ]
}

但是id有缺省值,所以有问题。

EN

回答 1

Stack Overflow用户

发布于 2021-03-12 13:46:00

似乎您可以在模型中显式指定uuid格式。这是来自drf docs关于UUID的内容:

代码语言:javascript
运行
复制
Signature: UUIDField(format='hex_verbose')

format: Determines the representation format of the uuid value
'hex_verbose' - The canonical hex representation, including hyphens: "5ce0e9a5-5ffa-654b-cee0-1238041fb31a"
'hex' - The compact hex representation of the UUID, not including hyphens: "5ce0e9a55ffa654bcee01238041fb31a"
'int' - A 128 bit integer representation of the UUID: "123456789012312313134124512351145145114"
'urn' - RFC 4122 URN representation of the UUID: "urn:uuid:5ce0e9a5-5ffa-654b-cee0-1238041fb31a" Changing the format parameters only affects representation values. All formats are accepted by to_internal_value
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66594627

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档