Create UUID on client and save primary key with Dj

2019-02-08 14:29发布

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.

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.

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.

Is this possible?

My stack is

  • Django 1.8

  • Django Rest Framework 3.1

Here is the code.

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

1条回答
劫难
2楼-- · 2019-02-08 15:10

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

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

Try declaring it explicitly:

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')
查看更多
登录 后发表回答