在Django中查询多个表

时间:2014-01-02 21:19:56

标签: python database django

我是Django和Python的初学者,我开始开发调查应用程序。它基于https://github.com/jessykate/django-survey 我添加了一些功能,但我遇到了结果页面的问题,更准确地说是如何 获取数据来呈现它们。以下是最重要字段的模型:

class Survey(models.Model):
    name = models.CharField(max_length=250)

class Question(models.Model):
    text = models.TextField()
    survey = models.ForeignKey(Survey)
    choices = models.TextField()

class Response(models.Model):
    survey = models.ForeignKey(Survey)

class AnswerBase(models.Model):
    question = models.ForeignKey(Question)
    response = models.ForeignKey(Response)  

class AnswerText(AnswerBase):
    body = models.TextField(blank=True, null=True)

class AnswerRadio(AnswerBase):
    body = models.TextField(blank=True, null=True)

    and few more Answer.. 

我认为这种格式的数据可以在js中稍后处理并显示为bar char:

results = [{'some_question_text':
            [{'answer':'answer1','count': 11},{'answer':'answer2','count': 6}, ..]}
          ,..]

我不能用django的方式来做这件事,所以我在sql中尝试过。问题是,它只适用于一种答案类型,当我添加另一个条件,如'或ab.id == polls_answerselect.answerbase_ptr_id'查询返回奇怪的结果。

这就是我所做的:

cursor = connection.cursor()
cursor.execute("select q.text as qtext, ar.body as ans, ab.id as Aid, q.id as Qid, count(ar.body) as count \
            from polls_answerbase ab, polls_answerradio ar, polls_question q, polls_survey s \
            where ab.id==ar.answerbase_ptr_id \
            and ab.question_id==q.id \
            and s.id==q.survey_id \
            group by ar.body")
rows = dictfetchall(cursor)
result = {}
for r in rows: 
    res[r['qtext']] = []
    res[r['qtext']].append({'ans': r['ans'], 'count': r['count']})

解决问题的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

看起来你想要的是一个按调查过滤的问题列表,你想要它以json格式。

看看http://django-rest-framework.org/它带有一组预定义的基于类的视图,支持多种响应格式,json就是其中之一。该网站上的教程将引导您完成设置,并在整个过程中使用简单的测试来验证您的操作是否正确。您可以为您的模型做类似的事情。

我也是Python / Django初学者,发现很容易上手。