bonobo
bonobo

Reputation: 13

Querying multiple tables in Django

I'm beginner in Django and Python, I started developing survey app. It's based on https://github.com/jessykate/django-survey I added few features, but I'm having problem with results page, to be more precisely how to get data to present them. Here's what models with most important fields look like:

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.. 

I think data in this format would be good to process later in js and display as bar char:

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

I could't came up how to do it in django way, so i tried in sql. Problem is, it works only with one answer type, when I add another condition like 'or ab.id==polls_answerselect.answerbase_ptr_id' query returns strange results.

Here's what I've done:

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']})

What is better and correct way to solve my problem?

Upvotes: 1

Views: 2480

Answers (1)

theraju
theraju

Reputation: 461

It looks like what you want here is a question list filtered by survey, and you want it in json format.

Take a look at http://django-rest-framework.org/ It comes with a set of predefined class based views that support multiple response formats, json being one of them. The tutorial on that site walks you through setting it up, and uses simple tests along the way to verify you're doing it right. You can do something similar for your models.

I'm a Python/Django beginner as well and found it very easy to pick up.

Upvotes: 1

Related Questions