Home > Net >  How to have an object's pk as an integer?
How to have an object's pk as an integer?

Time:05-25

I have this model:

class Class(models.Model):
    class_id = models.IntegerField(blank=False)

    def save(self, *args, **kwargs):
        self.class_id = self.pk 1000
        super(Class, self).save(*args, **kwargs)

As you can see, I want pk to be added to 1000 and use that as class_id value. But I get this error:

TypeError at /new-class

unsupported operand type(s) for  : 'NoneType' and 'int'

How can I have the pk as an integer?

CodePudding user response:

pk is an integer, but it does not get set until after the model is created since it comes from a sequence in the database.

You can also use the boolean self._state.adding to determine whether or not the model has already been created.

CodePudding user response:

You get this error because the id is None before you have saved the instance to the database.

In any case, why store this value to the database if it's always id 1000. You could use a property instead.

class Class(models.Model):

    @property
    def class_id(self):
        return self.pk and self.pk   1000

If you want to use your original approach, you must modify the save method.

def save(self, *args, **kwargs):
    if self._state.adding:
        # save once to get a id
        super().save(*args, **kwargs)
    self.class_id = self.pk   1000
    super().save(*args, **kwargs)
  • Related