django:关于查询模型的noob问题

时间:2011-05-02 09:00:53

标签: django django-models

我有以下表格:

class SchoolClass(models.Model):
    id = models.AutoField(primary_key = True)
    class_name = models.TextField()
    level = models.IntegerField()
    taught_by = models.ManyToManyField(User,related_name="taught_by",through='TeachSubject')
    attended_by = models.ManyToManyField(User,related_name='attended_by')

class ConsentFormTemplate(models.Model):
    title = models.TextField()
    body = models.TextField()
    teacher_id = models.ForeignKey(User)
    consent_id = models.AutoField(primary_key = True)

    class Meta:
        db_table = "consent_form_template"

class ConsentForm(models.Model):
    student_id = models.ForeignKey(User)
    remarks = models.TextField()
    #class_id = models.ForeignKey(SchoolClass)

    reply = models.NullBooleanField()
    parents_remark = models.TextField()
    tpl = models.ForeignKey(ConsentFormTemplate)
    acknowledged_by = models.ForeignKey(User,related_name='acknowledged_by',null=True,blank=True)
    acknowledged_on = models.DateField(auto_now=True,auto_now_add=True,null=True)
    date_sent = models.DateField(auto_now=True,auto_now_add =True)
    class Meta:
        unique_together = ('tpl_id','studentId')

    class Meta:
        db_table = "consent_form"

鉴于consentformtemplate的pk,我如何构建我的ORM查询,以便我的结果如下:

first_name(student) | class_name

1 个答案:

答案 0 :(得分:0)

consentformtemplate=ConsentFormTemplate.objects.get(pk=consentformtemplate_pk)

consents = ConsentForm.objects.filter(tpl=consentformtemplate).select_related()

for consent in consents:
    print "%s | %s" % (consent.student_id.first_name, consent.class_id.class_name)