2011-02-07 3 views
0

나는 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.') 

여기 를 업데이트 작동 상태 방법이다 : (? AttributeError를)

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 

답변

0

이 존재하지해야하는 models.JournalResponse를 참조하고처럼 보이는 때문에 클래스 정의에서 동일한 models을 가리키는 이름은 django.db.models

입니다.

실제 모델 객체를 통해 참조해야하므로 JournalResponse.objects.filter()입니다. 귀하의 경우에는

, 당신은 그래서 당신은 간단하게 액세스 할 수 self.journalresponse_set.filter()을 사용할 수 있습니다 Student에서 JournalResponse에 역의 관계를 가지고 JournalResponse.objects.filter(student=self) http://docs.djangoproject.com/en/dev/topics/db/queries/#following-relationships-backward

시도 :

또한
self.journalresponse_set.filter(field__journal=self.assignment) 

, 다음 필터 라인으로 휴식 것이 잘 text!=None에 있습니다. 대신 exclude(text=None) 구문을 사용하십시오.

+0

문제는 오류가 발생하지 않는다는 것입니다. 따라서 내 문제는 디버깅. – selfsimilar

+1

아, 제 사과! 그래,'models.JournalResponse' 라인이'AttributeError'를 바로 던지지 않는 것은 매우 이상합니다. 'import pdb; pdb.set_trace()'를'status' 정의 안에 넣고 정확한 쿼리를 실행하기 시작했습니다. 내 제안에 곧바로 시도해 볼 수 있습니다. –

+0

구조에 pdb, 감사합니다! 문제는 import 문이었습니다 :'from django.contrib.gis.db import models'은 모델 클래스 호출을 오버로드했습니다. 문제의 라인에서'models.'을 제거한 후 원래 코드가 작동했습니다. 이제 관계를 거꾸로 뒤집을 것에 대한 귀하의 제안을 시도해보십시오. – selfsimilar

관련 문제