Search code examples
djangopython-2.7django-1.9

UUIDField has no attribute uuid4


Here is my model

from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
import uuid

class PiO(models.Model): 
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) # surrogate
    person = models.ForeignKey(Person, on_delete=models.PROTECT, max_length=25, blank=True)
    content_type = models.ForeignKey(ContentType, on_delete=models.PROTECT) # for the various organization types
    object_id = models.UUIDField(primary_key=False, default=uuid.uuid4, editable=False) # the uuid of the specific org
    content_object = GenericForeignKey('content_type', 'object_id')

Here is my traceback

AttributeError: 'UUIDField' object has no attribute 'uuid4'.

Note this is specifically referencing the object_id field, not the uuid (pk) field. As a test, I commented out the object_id field. I did not get an error for not having an object_id field, and the check went on to a new error 12 lines away.

I googled the exact phrase and got

No results found for "AttributeError: 'UUIDField' object has no attribute 'uuid4'".

What I did looks consistent with the docs to me.

What am I missing? Does the presence of the generic foreign key and or the contenttype have anything to do with it?


Solution

  • The problem is that your model field uuid is clashing with the module uuid.

    One option would be to rename your model field, for example:

    class PiO(models.Model): 
        id = models.UUIDField(primary_key=True, default=uuid4, editable=False)
        ...
    

    Another option would be to change the import to from uuid import uuid4, and update the defaults to use uuid4 instead of uuid.uuid4.

    from uuid import uuid4
    
    class PiO(models.Model): 
        uuid = models.UUIDField(primary_key=True, default=uuid4, editable=False) # surrogate
        ...
        object_id = models.UUIDField(primary_key=False, default=uuid4, editable=False) # the uuid of the specific org