andriy
andriy

Reputation: 29

How to write Foreign Key to an attribute of other model?

I want to create a model that joins two tables in my DB. When writing the foreign keys like this:

fromnode = models.ForeignKey(znode.code)
tonode = models.ForeignKey(znode.code)

there is an error: type object 'znode' has no attribute 'code', but there is such an attribute in znode:

class znode(models.Model):
    code = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, primary_key=True)

How do I write this correctly?

Upvotes: 0

Views: 52

Answers (1)

timo.rieber
timo.rieber

Reputation: 3867

Just use the class name znode instead of znode.code. Django automatically adds an id column to every model which will be used as reference as mentioned in the documentation.

Behind the scenes, Django appends "_id" to the field name to create its database column name. In the above example, the database table for the Car model will have a manufacturer_id column.

Also you should use CamelCaseClassNames to meet pep8 coding style conventions.

Upvotes: 1

Related Questions