Skip to content
Advertisement

Code to display Django (Reverse) related table throws error

I’m quite new to Django and practicing Models section of Django by following its official tutorial. I also created a project of my own and try to apply similar concepts.

This is my models.py;

JavaScript

Now when I run below command in Python/Django shell it runs as expected with the related data.

JavaScript

Below two also work as expected:

JavaScript

However this expression does not return anything although it should return its related record in Experience Class.

JavaScript

Could you tell me what I am missing here?

Advertisement

Answer

As you mentioned in one of the comments above:

Strangely it returns this; Traceback (most recent call last): File “”, line 1, in AttributeError: ‘Prjdesc’ object has no attribute ‘experience’.

You simply need to write c.o00_key not c.experience, you confused with official docs, they give their field name also as experince.

Generally, ForeignKey is created using model name in smallcase while defining field, and the related_name sets to model name as prefix and _set as suffix by default, so it will be prjdesc_set in your case or you can override it by using ForeignKey.related_name in the field.

With your current models use this:

JavaScript

Note: Also it’s better to use f stings in the __str__() method, so in your models.py:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement