I can do this:
counter = 0
class A(models.Model):
code = models.IntegerField(max_length=30, default=generate_code)
def generate_code():
counter += 1
return counter
But it seems to be, that the assignment is done during the initialization (loading) of the model class, not at creating an instance, so ‘code’ is always ‘1’.
How can I automatically assign a dynamic value to some field during creating an instance of a model class?
If I set the value in an overriden __init__ function, like this:
class A(models.Model):
def __init__(self, *args, **kwargs):
models.Model.__init__(self, *args, **kwargs)
self.code = self.generate_code()
The code is change on every update. As the debugger shows me, the __init__ function is also called, when I delete the object. I really do not understand this!
I can set the code in the __init__ function only, if it is not set, but that seems to be illogical, so I like to avoid it.
Are you just looking for a way to make sure that each of the A objects in your database has a unique counter value? Then you can use
AutoFieldinstead ofIntegerField:https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.AutoField
When you create a new
Aobject, itscountervalue will be automatically set to one higher than the previously created one.To explain some of the behavior you’re seeing, each time your models.py is loaded, it will indeed initialize a new
countervariable to 0, as you figured out. As for why theAconstructor is being called when you don’t expect it,Ais just a class representing some data from the database. So every time Django gets data out of the database and presents it to you, it’s creating a newAobject to encapsulate that data.