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

1👍

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.

Leave a comment