3π
β
The problem is that you set the index
before saving the instance, at that point, new model instance do not yet have an id
. So you can perform two .save()
s: one before obtaining the id
, and one to save
the new index.
def save(self, *args, **kwargs):
if self.id is None:
super().save(*args, **kwargs)
if self.index is None:
self.index = self.id
super().save(*args, **kwargs)
But that being said, it is still not a good idea: there are various ways to circumvent the .save(..)
method, for example when updating specific fields, etc.
Therefore I advice you to make a column _index
instead that is NULL
-able, and then write a @property
to handle the case where the index
is NULL
:
class PhotoManager(models.Model):
id = models.AutoField(primary_key=True)
_index = models.PositiveIntegerField(null=True, default=None, blank=True)
@property
def index(self):
if self._index is not None:
return self._index
return self.id
0π
You should use parentheses, when calling function
index = models.PositiveIntegerField(default = model_instance_id(), blank=True, unique = False)
π€Ali
- [Django]-Convert raw SQL Query to Django QuerySet
- [Django]-Caught TypeError while rendering: 'BoundField' object is not iterable
- [Django]-ImportError for django.contrib.markup
- [Django]-Django β designing models with virtual fields?
Source:stackexchange.com