(For all instances of) Django model field 'moves', it maps to the same Move class instance

StackOverflow https://stackoverflow.com/questions/22993699

  •  01-07-2023
  •  | 
  •  

Pergunta

heres my model

class Game(models.Model):
    ...
    moves = Moves()

class Moves():
    moves = []
    ...

After creating about 50 objects of Game, all of them point to the same Moves() object. I need different instances of Moves for each object.

Here are game objects and their id along with moves:

1 :  <games.models.Moves object at 0x9f1474c>
2 :  <games.models.Moves object at 0x9f1474c>
3 :  <games.models.Moves object at 0x9f1474c>
...
Foi útil?

Solução

The problem is that both Game.moves and Moves.moves are class attributes and not instance attributes. This means that they are initialized only when class is created and not upon instance creation. To get the desired behavior use __init__ method:

class Game(models.Model):

    def __init__(self):
        self.moves = Moves()

class Moves():

    def __init__(self):
        self.moves = []

Here is what I get from interactive Python interpreter:

>>> class Game(models.Model):
...     def __init__(self):
...         self.moves = Moves()
... 
>>> class Moves():
...     def __init__(self):
...         self.moves = []
... 
>>> Game().moves
<__main__.Moves instance at 0x7f4ee1b9f560>
>>> Game().moves
<__main__.Moves instance at 0x7f4ee1b9f680>
>>> Game().moves
<__main__.Moves instance at 0x7f4ee1b9f560>

You can not simply create other instance attributes like Django does with Field subclasses defined as class attributes of Model subclasses.
Django provides a metaclass for Model which scans class attributes and converts them to instance attributes but only if they subclass Field.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top