Importing data from scanned text into Django as YAML fixture or SQL

╄→尐↘猪︶ㄣ 提交于 2019-12-11 09:06:49

问题


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.


回答1:


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 =)



来源:https://stackoverflow.com/questions/7669550/importing-data-from-scanned-text-into-django-as-yaml-fixture-or-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!