Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 8th, 2012  |  syntax: None  |  size: 1.51 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Django three way join using Foreign Keys
  2. Model:
  3.  
  4. class Product(models.Model):
  5.     productid = models.IntegerField(primary_key=True, db_column='ProductId')
  6.     productname = models.CharField(max_length=120, db_column='ProductName')
  7.  
  8. class Testcases(models.Model):
  9.     testcaseid = models.IntegerField(primary_key=True, db_column='TestCaseId')
  10.     testcasename = models.CharField(max_length=240, db_column='TestCaseName')
  11.  
  12. class Testmatrix(models.Model):
  13.     testmatrixid = models.IntegerField(primary_key=True, db_column='TestMatrixId')
  14.     productid = models.ForeignKey(Product, db_column='ProductId')
  15.     testcaseid = models.ForeignKey(Testcases, db_column='TestCaseId')
  16.  
  17. class Status(models.Model):
  18.     testmatrixid = models.ForeignKey(Testmatrix, db_column='TestMatrixId')
  19.     title = models.CharField(max_length=240, db_column='Title', blank=True)
  20.        
  21. View:
  22.  
  23. from django.shortcuts import render_to_response
  24. from mysite.testmatrix.models import Product, Testcases, Testmatrix, Status
  25.  
  26. def get_products(request):
  27.     tm = list(Testmatrix.objects.filter(productid='abc'))
  28.     return render_to_response('products.html', {'tm': tm})
  29.        
  30. Template: (products.html)
  31. {% extends "main.html" %}
  32.  
  33. {% block body %}
  34. <table>
  35. {% for tm in tm %}
  36.     <tr>
  37.             <td>{{ tm.testmatrixid }}</td>
  38.     <td>{{ tm.testcaseid.testcasename }}</td>
  39.     </tr>
  40. {% endfor %}
  41. </table>
  42. {% endblock %}
  43.        
  44. class Status(models.Model):
  45.     testmatrixid = models.ForeignKey(Testmatrix, db_column='TestMatrixId', related_name='statuses')
  46.        
  47. test_matrix.statuses.all()