2๐
Well we can first load a dictionary that maps id
s to choice_text
:
mapping = dict(Choice.objects.filter(pk__in=votes.keys())
.values_list('pk', 'choice_text'))
Here with pk__in
we thus make a filter (which is, strictly speaking, not necessary, but will reduce the amount of work both for the database and the webserver, unless the number of id
s is huge). Then we want it to return values_list
s, so for every element a list with two elements: the pk
and the choice_text
.
We use the dict(..)
constructor, which can fetch an iterable of 2-lists (or 2-tuples), and converts it to a dictionary where for every element the left item of the sublist/tuple is the key, and the right item is the value.
Now we can use this to construct a new dictionary:
votes_with_text = {mapping[int(k)]: v for k, v in votes.items()}
Note that in case there are two Choice
s with the same choice_text
, then it will only retain one of the elements in the counter.
In case the choice_text
s should be different for every two Choice
s with the same question
, you can enforce that at the model level with unique_together
:
class Choice(models.Model):
question = models.ForeignKey(Poll, on_delete=models.CASCADE)
choice_text = models.CharField(max_length=200)
class Meta:
unique_together = (('question', 'choice_text'), )
3๐
to get the name of your choice :
choice_text = Choice.objects.get(pk=choice_id)
so you have to iterate over your ids, get the choice_text and use :
votes[choice_text] = votes.pop(choice_id)
to rename your keys to the corresponding choice names.
- [Django]-Django "manage.py index" does not execute as a cron job
- [Django]-Storing multiple values into a single field in mysql database that preserve order in Django