Create UUID on client and save primary key with Django REST Framework and using a POST
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 Rest Framework 3.1
Here is the code.
class PersonCreateSerializer(serializers.ModelSerializer): class Meta: model = Person fields = ('id', 'username', 'email', 'password')
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):
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')