Django和2个问题

时间:2011-12-21 16:54:21

标签: django

这是我的模特:

from django.db import models
from depot.models import Subject, Student

# Create your models here.
class Credit(models.Model):
    subject = models.ForeignKey(Subject)
    number = models.IntegerField()
    first_level_questions = models.IntegerField(default=8)
    second_level_questions = models.IntegerField(default=8)
    third_level_questions = models.IntegerField(default=4)

class Question(models.Model):
    credit = models.ForeignKey(Credit)
    question = models.CharField(max_length=200)
    level_choice = (
        (1, u'1'),
        (2, u'2'),
        (3, u'3'),
    )
    level = models.IntegerField(choices=level_choice)
    a = models.CharField(max_length=200, blank=True)
    b = models.CharField(max_length=200, blank=True)
    c = models.CharField(max_length=200, blank=True)
    d = models.CharField(max_length=200, blank=True)
    right_answer_choices = (
        (1, u'a'),
        (2, u'b'),
        (3, u'c'),
        (4, u'd'),
    )
    right_answer = models.IntegerField(choices=right_answer_choices, blank=True)

class Answer(models.Model):
    question = models.ForeignKey(Question)
    student = models.ForeignKey(Student)
    answer = models.CharField(max_length=400)
    right = models.BooleanField(default=None)

    def __unicode__(self):
        return self.answer

class Mark(models.Model):
    student = models.ForeignKey(Student)
    credit  = models.ForeignKey(Credit)
    total = models.IntegerField()

这是我的admin.py:

from django.contrib import admin
from credits.models import Credit, Question

class QuestionInline(admin.StackedInline):
    model = Question
    extra = 0

class CreditAdmin(admin.ModelAdmin):
    list_display = ['subject', 'number']
    inlines = [QuestionInline,]


admin.site.register(Credit, CreditAdmin)

我解决了我的第一个问题。谢谢。 我的第二个问题: 我想在我的标记模型中有一个方法。 你知道的是:

def total_mark(self):
    return Answer.objects.filter(student=self.student, right=True).count()

但信用呢?我需要确切的学生和确切的学分。

1 个答案:

答案 0 :(得分:0)

对于您的第一个问题,我认为这与ChoiceField具有值''(空字符串)的事实有关,如果没有选择任何内容。这是您正在创建的两个选项字段的问题,因为它们需要整数,但它们无法将''转换为整数。我认为当您提交表单时会出现此错误?提交时是否选择了right_answer?我会尝试从该字段中删除blank=True - 毕竟,每个问题都应该有正确答案!


关于你的第二个问题,你可能想要在你看来这样的事情:

# given a student object s
correct_answers = Answer.objects.filter(student=s, right=True).count()
# now you can save the mark how you want