У меня есть следующие классы: 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
Проблема в том, что ошибка не возникает. Следовательно, мои проблемы отлаживаются. – selfsimilar
А, мои извинения! Да, очень странно, что строка 'models.JournalResponse' не бросает' AttributeError' сразу. Я бы поставил 'import pdb; pdb.set_trace()' внутри определения 'status' и начал выполнять ваш точный запрос. Вы могли бы попытаться сразу перейти к моему предложению и посмотреть, работает ли он так же хорошо. –
pdb на помощь, спасибо! Проблема заключалась в заявлении на импорт: 'из моделей импорта django.contrib.gis.db', которые перегружали вызов класса моделей. после того, как я удалил «models.» с нарушающих строк, работал исходный код. Теперь попробуем ваше предложение относительно последующих отношений. – selfsimilar