I'm trying to define a custom variable inside a django model class that depends on a related object. Here is a simplified version of my code:
class Vm(models.Model):
position = models.OneToOneField('Position', null=True, blank=True, default = None)
def __init__(self, *args, **kwargs):
models.Model.__init__(self)
self.port = 5000+10*(self.position.position-1)
class Position(models.Model):
position = models.IntegerField()
So when I initialize a Vm object, I want to access its 'port' attribute that depends on its related foreign key 'position'.
Vm object and corresponding Position object are already created and stored in DB. When I'm trying to initialize a Vm object vm = Vm.objects.get(pk=1)
I get the error AttributeError: 'NoneType' object has no attribute 'position'
like the position object has not been initialized yet. How can I do it?