Django模型ORM外键关系

时间:2011-12-26 09:02:17

标签: orm django-models

我有三节课。我有accountid,我必须使用Django ORM检索courtName和CaseName。请帮我写一个查询。

模型类

 class Court1(models.Model):
    CourtID = models.IntegerField(primary_key=True)
    CourtTypeID = models.IntegerField()
    CourtName = models.CharField(max_length=150)    
    class Meta:
       db_table = u'Court1'

 class CaseSummary1(models.Model):
   CaseID = models.AutoField(primary_key=True)
   CaseName = models.CharField(max_length=500,null=True, blank=True)
   DateFiled=models.DateField(null=True, blank=True)
   class Meta:
     db_table = u'CaseSummary1'

  class PacerDocument1(models.Model):
   DocumentID = models.AutoField(primary_key=True)
   PacerDocID = models.CharField(max_length=250)
   CourtID = models.ForeignKey(Court1)
   CaseID = models.ForeignKey(CaseSummary1)
   class Meta:
     db_table = u'PacerDocument1'



class DocumentAccess1(models.Model):
   AccountID = models.AutoField(primary_key=True)    
   DocumentID = models.ForeignKey(PacerDocument1)    
   class Meta:
     db_table = u'DocumentAccess1'

Sql Query

select CourtNAme,CaseName 
from documentaccess1 a,pacerdocument1 b,Court1 c,CaseSummary1 d  
where b.caseID_id  = d.CaseID 
  and b.CourtID_id = c.CourtID 
  and a.AccountID  = 1

1 个答案:

答案 0 :(得分:0)

Django使用一种聪明的方式来进行查询:你只需要调用一个类似的方法     court = Court.objects.filter(case__id = ...) 如果这是你在Django的第一个项目,你应该阅读this