如何从其他模型函数进行模型查询?

时间:2011-02-07 20:16:38

标签: django django-models

我有以下课程:Student,LabJournal,JournalResponse和JournalField。我想为学生定义一个“状态”功能,以确定他们已经回答了多少问题(JournalField)(JournalResponse)。问题是函数在以下行没有返回时死掉:

total_questions = models.JournalResponse.objects.filter(owner__exact=self.id).filter(field__journal__exact=self.assignment).count()

我的猜测是我在类定义中做错了模型查询,或者你不允许在单独的模型中查询。但是我没有在文档中找到任何确认或否认这一点的内容,并且没有任何错误,很难调试。运行Django 1.1。

以下代码:

class Student (models.Model):
    user = models.ForeignKey(User, unique=True, null=False, related_name='student')
    teacher = models.ForeignKey(User, null=False, related_name='students')
    assignment = models.ForeignKey(LabJournal, blank=True, null=True, related_name='students')

    def get_absolute_url(self):
        return "/labjournal/student/%i/" % self.id

    def status(self):
        if self.assignment == None : return "unassigned"
        percent_done = 0
        total_questions = models.JournalResponse.objects.filter(owner__exact=self.id).filter(field__journal__exact=self.assignment).count()
        answered_questions = models.JournalResponse.objects.filter(owner__exact=self.id).filter(field__journal__exact=self.assignment).filter(text!=None).count()
        percent_done = (answered_questions/total_questions)*100
        return '%d%% done' % percent_done

class JournalResponse (models.Model):
    owner = models.ForeignKey(Student, null=False, related_name='responses')
    field = models.ForeignKey(JournalField, null=False, related_name='responses')
    text = models.TextField(null=True, blank=True)
    file = models.URLField(null=True, blank=True)


class JournalField (models.Model):
    TYPE_CHOICES = (
        (u'HTML', u'HTML'),
        (u'IF', u'ImageField'),
        (u'TF', u'TextField'),
    )

    journal = models.ForeignKey(LabJournal, null=False, related_name='fields', help_text='Parent Journal')
    ordinal = models.IntegerField(help_text='Field order')
    type = models.CharField(null=False, max_length=64, choices=TYPE_CHOICES, help_text='Field type')
    # Contains HTML content for HTML fields, contains the text marked "question" closest
    # to and above the current field for picture and text entry fields
    content = models.TextField(help_text='Should contain HTML content for HTML (question) fields or associated (previous question) HTML for ImageFields and TextFields.')

已更新 这是工作状态方法:

def status(self):
    if self.assignment == None : return "unassigned"
    percent_done = 0
    # sets up query, but doesn't actually hit database
    response_set = self.responses.filter(owner=self).filter(field__journal=self.assignment)
    # force float so divide returns float
    # the two count statements are the only two actual hits on the database
    total_questions = float(response_set.count())
    answered_questions = float(response_set.exclude(text='').count())
    percent_done = (answered_questions/total_questions)*100
    return '%d%% done' % percent_done

1 个答案:

答案 0 :(得分:0)

看起来你指的是不应该存在的models.JournalResponse(AttributeError?),因为在类定义中,相同的models名称是指django.db.models

您需要通过实际的模型对象来引用它,所以JournalResponse.objects.filter()

在您的情况下,您与JournalResponse的{​​{1}}有反向关系,因此您只需使用Student即可访问self.journalresponse_set.filter() http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

尝试:

JournalResponse.objects.filter(student=self)

此外,您的下一个过滤行也会在self.journalresponse_set.filter(field__journal=self.assignment) 上中断。请改用text!=None语法。