Titouan
Titouan

Reputation: 15

Django models objects return None

I have this model in my Django app.

class Kilometer(models.Model):
    kilometers = models.IntegerField()

It work when with a form I save data on my database (I can see the objects on the admin page) but I have issue when I want to access the data in django shell.

>>> from forms.models import Kilometer
>>> test = Kilometer(1)
>>> print(test)
Kilometer object (1)
>>> print(test.kilometers)
None

I have the same problem with all my models.

Upvotes: 1

Views: 702

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477883

The 1 is the primary key, if you want to construct a Kilometer with as kilometers = 1, you construct this with:

test = Kilometer(kilometers=1)

or you can work with a positional parameter where the primary key is set to None:

#     primary key ↓
test = Kilometer(None, 1)
#           kilometers ↑

Or if you want to determine the kilometers of an record with primary key 1 for example, you can fetch the Kilometer object with:

kms = Kilometer.objects.get(pk=1)

you can also reduce the bandwidth if you are only interested in the kilometers with:

kms = Kilometer.objects.only('pk', 'kilometers').get(
    pk=1
)

regardless how you fetch the Kilometer object, you can then fetch the number of kilometers with:

kms.kilometers

Upvotes: 3

Related Questions