Pergunta

I'm setting up a simple Django app -- a quiz. The questions and answers come from printed sample tests that have been scanned, OCR'd and parsed. I've parsed them into Python objects like so:

class Quiz(object):
    def __init__(self, name):
        self.name = name
        self.questions = {}
class Question(object):
    def __init__(self, text):
        self.text = text
        self.answers = {}
class Answer(object):
    def __init__(self, text, value= -1.0, explanation=""):
        self.text = text
        self.value = value
        self.explanation = explanation

but my Django models, being unable to have "lists" as model fields use foreign keys to keep the relationship between quiz-

class Quiz(models.Model):
    name = models.CharField(max_length=256)
class Question(models.Model):
    quiz = models.ForeignKey(quiz)
    order = models.IntegerField()
    text = models.TextField()
class Answer(models.Model):
    question = models.ForeignKey(question)
    order = models.IntegerField()
    text = models.TextField()
    explanation = models.TextField()
    value = models.FloatField()

Could someone suggest a straightforward way to go from the former to the latter? Thanks.

Foi útil?

Solução

The first question to ask yourself is why you are using these intermediate classes at all? This sounds like bad design.

Once we move past the bad design. Your code shows that qustion.answers is a dictionary not a list, I assume you just made a typo.

If you have a Quiz model instance you can call Quiz.question_set.all() to get all questions for that quiz. The result of this call will be a queryset, which is an iterable object and as such calling list(Quiz.question_set.all()) will give you a list.

I can't emphasize enough though that you're doing it wrong and should most likely just be doing away with the middleman. Also PEP8 naming rules are very much a good idea to follow, ie classes are named like so:

class Quiz(models.Model):
    ...

It will make your life easier to follow the conventions =)

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top