Background Image
Table of Contents Table of Contents
Previous Page  127 / 478 Next Page
Information
Show Menu
Previous Page 127 / 478 Next Page
Page Background

self.assertEqual(first_saved_item.list, list_)

AttributeError: 'Item' object has no attribute 'list'

A Foreign Key Relationship

How do we give our

Item

a list attribute? Let’s just try naively making it like the

text

attribute:

lists/models.py.

from

django.db

import

models

class

List

(

models

.

Model

):

pass

class

Item

(

models

.

Model

):

text

=

models

.

TextField

(

default

=

''

)

list

=

models

.

TextField

(

default

=

''

)

As usual, the tests tell us we need a migration:

$

python3 manage.py test lists

[...]

django.db.utils.OperationalError: table lists_item has no column named list

$

python3 manage.py makemigrations

Migrations for 'lists':

0004_item_list.py:

- Add field list to item

Let’s see what that gives us:

AssertionError: 'List object' != <List: List object>

We’re not quite there. Look closely at each side of the

!=

. Django has only saved the

string representation of the

List

object. To save the relationship to the object itself, we

tell Django about the relationship between the two classes using a

ForeignKey

:

lists/models.py.

from

django.db

import

models

class

List

(

models

.

Model

):

pass

class

Item

(

models

.

Model

):

text

=

models

.

TextField

(

default

=

''

)

list

=

models

.

ForeignKey

(

List

,

default

=

None

)

That’ll need amigration too. Since the last onewas a red herring, let’s delete it and replace

it with a new one:

$

rm lists/migrations/0004_item_list.py

$

python3 manage.py makemigrations

Migrations for 'lists':

Adjusting Our Models

|

99