python - 在 Django 中查询多个表

标签 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中处理并显示为条形字符会很好:

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

我无法想出如何以 django 方式做到这一点,所以我尝试了 sql。问题是,它仅适用于一种答案类型,当我添加另一个条件(如“or 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']})

什么是更好、正确的方法来解决我的问题?

最佳答案

看起来您想要的是一个通过调查过滤的问题列表,并且您希望它是 json 格式。

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

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

关于python - 在 Django 中查询多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20892096/

相关文章:

mongodb - 数据库条目的高效唯一 key 生成

python - django Translation.activate() 接受什么语言格式?

python - 将图像存储在 MongoDB 中

python - 根据精确文本匹配重新索引数据框

python - 在python中分配数组(列表)算法排列

sql - 如何在具有不同表结构的数据库之间复制数据?

javascript - 清除所有内容的 PostgreSQL 数据库

python - 反向修补的 django-localeurl 在单元测试中不起作用

python - 在 django rest 框架中对 ModelViewSet 的 PATCH 请求 - 我如何实现 serializer.update()?

python - 在 Python 中将列表从文本拆分为 nGram