1👍
When you do the assignment team.stage = 1
it only changes the stage
value of the instance that the variable team
is pointing to. Since it is not a model field, it won’t be stored in the database when you call .save()
method and, it won’t be persisted through multiple Team
instances.
Because of that, newly created teams won’t have any idea about the current value of stage
:
>>> t1 = Team()
>>> t1.stage = 1
>>> t2 = Team()
>>> print t2.stage
0
Also, it is a class variable, which means you can assign its value on class level, so that all instances created from it will be able to access the same value:
>>> Team.stage = 1
>>> t1 = Team()
>>> print t1.stage
1
>>> t2 = Team()
>>> print t2.stage
1
Since Team.objects.get(pk=1)
will always return a new instance every time it was called, holding a class variable won’t help you much, you have to use a model field, preferably models.IntegerField
, in order for all instances to have the same value for stage
.
1👍
stage = models.IntegerField(default=0)
Here stage
is a database field with int
type and default
constraint set to 0
. Django knows, how to manage this field.
stage = 0
Here stage
is a class field. Django does not know, how to manage it in the database layer. That is why Django skips this field.
Why can django get this attribute, but not set it?
Django is only a framework. Python manages all classes, objects and others. When it creates an object of your class, it initializes the field to zero.
- [Answered ]-After change class function doesn't work
- [Answered ]-Django bootstrap to have both call a view and modal in same anchor tag
- [Answered ]-Django JWT asking for username/password
- [Answered ]-Empty Chatterbot Conversation table in Django Admin