[Django]-How to match dictionary keys to model ids

2๐Ÿ‘

โœ…

Well we can first load a dictionary that maps ids 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 ids is huge). Then we want it to return values_lists, 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 Choices with the same choice_text, then it will only retain one of the elements in the counter.

In case the choice_texts should be different for every two Choices 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.

๐Ÿ‘คmadjaoue

Leave a comment