Django Rest Framework发布主键uuid或自动生成 [英] Django Rest Framework post primary key uuid or autogenerate
问题描述
以下链接帮助了我很多
所以,通过使用 id = serializers.UUIDField()
使传递一个ID。
如果缺少,它将不再自动生成。
So, by using id = serializers.UUIDField()
makes passing an ID required.
It will no longer autogenerate if on is missing.
我认为在这一点上,在任何序列化器上,我想要能够POST一个id,我需要要覆盖Create方法,如果在post数据中没有传递ID,那么在这里生成一个新的uuid并保存模型。
这是正确的吗?
OR
有没有DRF可以允许和id被传入或自动生成(如果不是)?
I assume at this point that on any serializer I want to be able to POST an id, I need to override the Create method and if no ID is passed in the post data, generate a new uuid there and save the model. Is this correct? OR Is there a way DRF can both allow for and id to be passed in or autogenerate if it is not?
编辑:我试过覆盖Create方法并生成一个新的uuid(如果它不存在),但看起来好像DRF首先检查数据仍然返回
I tried overriding the Create method and generating a new uuid if it is not present, but it appears as if DRF is checking the data first and still returns
{
"id": [
"This field is required."
]
}
Ps我不知道这是否完全相关,但是使用UUID作为主键的型号使用以下
P.s. I do not know if this is totally relevant but our models that use a UUID for the primary key are using the following
型号
class Company(models.Model):
id = PGUUIDField(primary_key=True)
和定义
class PGUUIDField(CharField):
def __init__(self, *args, **kwargs):
kwargs.setdefault('editable', not kwargs.get('primary_key', False))
kwargs.setdefault('default', uuid.uuid4)
kwargs.setdefault('max_length', 36)
super(PGUUIDField, self).__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super(PGUUIDField, self).deconstruct()
# Only include kwarg if it's not the default
return name, path, args, kwargs
def db_type(self, connection=None):
return 'uuid'
def get_db_prep_value(self, value, *args, **kwargs):
return self.to_python(value)
def to_python(self, value):
if not value:
return None
if not isinstance(value, uuid.UUID):
value = uuid.UUID("%s"%value)
return value
推荐答案
答案:
我可以覆盖 init 方法,并检查kwargs中的 kwargs ['data'] ['id']
如果不存在,请在调用超级类之前在kwargs中添加一个id字段。
I can override the init method and check the kwargs for an 'id' parameter in kwargs['data']['id']
and if it does not exist, add an 'id' field to kwargs before calling the super class.
class ControllerSerializer(serializers.ModelSerializer):
id = serializers.UUIDField()
class Meta:
model = Controller
fields = ('id', 'name', 'other_id')
def __init__(self, *args, **kwargs):
if kwargs['context']['request'].method == "POST":
try:
kwargs['data']['id']
except:
kwargs['data']['id'] = uuid.uuid4()
super(ControllerSerializer, self).__init__(*args, **kwargs)
所以现在我可以使用指定的id来POST POST!!!!
So now I can POST with a specified id or not!!!!
ps print语句仅用于调试
p.s. print statements are just for debugging
这篇关于Django Rest Framework发布主键uuid或自动生成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!