BlueSapphire BlueSapphire - 3 months ago 28
Python Question

Django JOIN with column renaming to queryset

I'm trying to build my django queryset with a join, and a colum-renaming. Unfortunately two fields of my have the same name, so the queryset does not return the values, as I expected it.

my models are like that:

class Question(models.Model):
text = models.CharField('Text', max_length=200, unique=True)

class UserQuestionnaire(models.Model):
creation = models.DateField('creation date')

class UserChoice(models.Model):
question = models.ForeignKey(Question)
questionnaire = models.ForeignKey(UserQuestionnaire)
text = models.CharField('Text', max_length=200) # same field name
votes = models.IntegerField(default=0)


My desired query for the output is like:
select * from polls_userchoice inner join polls_question;

which returns a table like that:

+----+-------------+------------------+------+-------+----+-------+
| id | question_id | questionnaire_id | text | votes | id | text |
+----+-------------+------------------+------+-------+----+-------+
| 1 | 1 | 3 | 2 | 0 | 1 | text1 |
| 2 | 4 | 3 | 6 | 0 | 2 | text2 |
| 3 | 3 | 3 | 6 | 0 | 3 | text3 |


My django queryset with

user_choice_list = UserChoice.objects.filter(
questionnaire=user_questionnaire.id).select_related('question')


returns only a dictionnary like this

[{'questionnaire_id': 3L, 'votes': 0L, 'text': u'2', u'id': 1L, 'question_id': 1L},
{'questionnaire_id': 3L, 'votes': 0L, 'text': u'6', u'id': 2L, 'question_id': 4L},
{'questionnaire_id': 3L, 'votes': 0L, 'text': u'6', u'id': 3L, 'question_id': 3L}]


So my question is, is it possible to rename the second 'text' column of the question model during the query so I can access it from the queryset methods?

Answer

You can use values() instead of select_related(). Such as

user_choice_list = userChoice.objects.filter(questionnaire=user_questionnaire.id).values('id' , 'question_id' , 'questionnaire_id', 'question__text', 'votes', 'text')
Comments