Django Rest Framework post primary key uuid or autogenerate

耗尽温柔 提交于 2020-01-15 07:36:48

问题


The following link helped me a lot

reference

So, by using id = serializers.UUIDField() makes passing an ID required. It will no longer autogenerate if on is missing.

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?

EDIT: 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."
 ]
}





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

model

class Company(models.Model):
id = PGUUIDField(primary_key=True)

and the definition

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

回答1:


Answer:

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)

So now I can POST with a specified id or not!!!!

p.s. print statements are just for debugging



来源:https://stackoverflow.com/questions/41747102/django-rest-framework-post-primary-key-uuid-or-autogenerate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!