2

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?

4

1 回答 1

0

That is because position is nullable, and if the value is None, you cannot access position attribute of None

One fix would be:

class Vm(models.Model):
    position = models.OneToOneField('Position', null=True, blank=True, default = None)
    def __init__(self, *args, **kwargs):
        super(Vm, self).__init__( *args, **kwargs)
        if self.position:
            self.port = 5000+10*(self.position.position-1) 
        else:
            self.port = 5000 #Or whatever the default you want to set.

Another approach:

class Vm(models.Model):
    position = models.OneToOneField('Position', null=True, blank=True, default = None)
    def __init__(*args, **kwargs):
        super(Vm, self).__init__(self, *args, **kwargs)

    def port(self):
        if self.position:
            return 5000+10*(self.position.position-1)
        else:
            return 5000 #or any default value you wish to specify.

And whenever you want to access port, do

vm = Vm.objects.get(pk=1)
port = vm.port()
于 2013-11-15T03:03:52.367 回答