n.imp
n.imp

Reputation: 807

Issues with UUID field in django admin

I am using UUID field as primary key for my models , eveything is working fine when I am adding data to models from my views but when I tried to add one row from admin it gives me error of empty string I think .

DataError at /admin/appname/modelname/add/
invalid input syntax for uuid: ""
LINE 1: ...053380+00:00' WHERE "tablename"."field" = ''

My UUID field looks like

pk_field = UUIDField(auto=True, primary_key=True, serialize=True, hyphenate=True)

Any solution ??

Upvotes: 0

Views: 1932

Answers (1)

danius
danius

Reputation: 2774

You may use native Django 1.8 UUIDField. In case you just want always to return non-hyphenated and serialized to string python object, you only have to subclass UUIDField and override from_db_value like this:

class CustomUUIDField(models.UUIDField):

    def from_db_value(self, value, expression, connection, context):
        if isinstance(value, uuid.UUID):
            return value.hex
        else:
            return value

Then use your CustomUUIDField instead native Django's UUIDField. Remember: this will ONLY work on Django 1.8, not prior versions (nor Django 1.7).

Upvotes: 1

Related Questions