在客户端创建UUID,并使用Django REST Framework保存主键并使用POST [英] Create UUID on client and save primary key with Django REST Framework and using a POST

查看:346
本文介绍了在客户端创建UUID,并使用Django REST Framework保存主键并使用POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要在客户端上创建一个 UUID 并将其发送到Django Rest Framework (DRF),并使用对于主键的模型。

I'd like to be able to create a UUID on the client and send it to Django Rest Framework (DRF) and use that for the Primary Key of the Model.

到目前为止,当我发送主在我的源代码中标有 id 的键,DRF忽略 id 并使用模型的默认参数生成一个新的 UUID

So far, when I send the Primary Key, which is labeled id in my source code, DRF ignores the id and uses the default argument of the Model to generate a fresh UUID.

然而,当我从模型测试时,使用正常的Django ORM创建对象,并预先设置 UUID ,模型接受 UUID ,因为它主键,不尝试重新创建一个新的。

However, when I test from the Model, using the normal Django ORM to create the object, and pre-set the UUID, the Model accepts the UUID as it's Primary Key and doesn't try and recreate a new one.

这是可能吗?

我的堆栈是


  • Django 1.8

  • Django 1.8

Django Rest Framework 3.1

Django Rest Framework 3.1

这是代码。

serializers.py:

class PersonCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Person
        fields = ('id', 'username', 'email', 'password')

models.py:

from django.contrib.auth.models import AbstractUser

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

class Person(AbstractUser, BaseModel):


推荐答案

串行器的 id 字段设置为只读,因为 editable = False 参数。

The id field of the serializer is set as read-only because of the editable=False argument.


具有editable = False设置的模型字段,AutoField字段将
默认设置为只读, p>

Model fields which have editable=False set, and AutoField fields will be set to read-only by default,

尝试明确声明:

class PersonCreateSerializer(serializers.ModelSerializer):
    # Explicit declaration sets the field to be `read_only=False`
    id = serializers.UUIDField()

    class Meta:
        model = Person
        fields = ('id', 'username', 'email', 'password')

这篇关于在客户端创建UUID,并使用Django REST Framework保存主键并使用POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆