Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if a model instance is new or not when using UUIDField as a Primary Key

I have a model that requires some post-processing (I generate an MD5 of the body field).

models.py

class MyModel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    body = models.TextField()
    md5 = models.CharField(max_length=32)
    ...

    def save(self, *args, **kwargs):
        if self.pk is None: # Only for create (edit disabled)
            self.md5 = get_md5(self.body)
            super(MyModel, self).save(*args, **kwargs)

The problem is that the final block won't execute because I don't see a way to check if the instance is new or not: self.pk is never None because a UUID is populated before saving.

I'd like to know what the best practice is for handling this.

Thanks in advance.

Update:

The only solution I can think of is to call the database directly and:

  1. Check if the id exists
  2. Compare the modified and created fields to tell if it's an edit
like image 867
Daniel van Flymen Avatar asked Dec 15 '15 07:12

Daniel van Flymen


1 Answers

EDIT

self.pk is never None because a UUID is populated before saving.

Instead of setting a default for id, use a method to set id for the new instance.

class MyModel(...):
    id = models.UUIDField(primary_key=True, default=None,...)

    def set_pk(self):
        self.pk = uuid.uuid4()

    def save(self, *args, **kwargs):
        if self.pk is None:
            self.set_pk()
            self.md5 = get_md5(self.body)
            super(MyModel, self).save(*args, **kwargs)
like image 96
xyres Avatar answered Oct 04 '22 14:10

xyres