[Answered ]-Django three way join using Foreign Keys


So you need to access a related_object. It is very simple.

First, add related_name here:

class Status(models.Model):
    testmatrixid = models.ForeignKey(Testmatrix, db_column='TestMatrixId', related_name='statuses')

Now you can get all the statuses for desired Testmatrix like


If you don’t want to hit DB, when you access statuses, don’t forget to use select_related.


Without any specific error messages, it is hard to diagnose the cause of said errors. However, in your example, in views.get_products: tm = list(Testmatrix.objects.filter(productid='abc')) will not work, because ‘abc’ is a string and your productid is actually a Product object (not just an integer, even though the field is an integer foreign key to your reference table’s pk); you can do tm = list(Testmatrix.objects.filter(productid=Product.objects.get(product_name='abc')), assuming that ‘abc’ is the product name of the product record. When you set a field to models.ForeignKey(…), you address that reference record as an object, not an id.

Other than that, nothing blaring, your template looks solid and your models look fine to me. I would suggest creating some test cases to see where the errors lie: Django Testing; Also, this is also a great tutorial to understand TDD and unit testing with Django. Using unittests, you can verify every step of your application and make future updates with assurance.

Leave a comment