0

If I have a queryset called Fruit, whose model is something like:

class Fruit(model.Models)
    name = models.CharField()
    producer = models.ForeignKey(Producer)

In my view, I have a dynamically created dictionary, called Fruit_Quality, which contains something like {'Orange' : 'ripe', 'Apple' : 'overripe', etc.}

I want to be able to pass both the query_set and the dictionary to the template, and loop through the query_set instances, to output lines that looks like:

{{ Fruit.name Fruit.producer.name Fruit.producer.location Fruit_Quality[Fruit.name] }}

The latter syntax to reference the fruit in the dictionary, is of course not a valid template syntax. Is there a valid syntax? I can't find any.

If there is no valid syntax, is there a way to loop through the query_set and dictionary, at the same time?

Note: Unfortunately I can't add the field "Fruit_Quality" to the model, because Fruit_Quality is dynamically created, and not meant to be stored. So that is not a solution.

Also, I would like to have Fruit passed to the template as a queryset, so that I can reference the fields of foreign keys in the model, such as the producer. If I didn't have that restriction, one could convert the queryset to a list of dictionaries in the view, and append Fruit_Qualtiy to each dictionary. But those foreign keys prevents me from easily converting the queryset to a dictionary (without adding all the foreign key fields to the dictionary also).

Thanks for any suggestions.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
user1993015
  • 334
  • 1
  • 2
  • 16
  • 1
    Add property dynamically to model itself instead create alone dictionary: `fruit = Fruit.objects.get( pk = 3 )`; `fruit.quality = "ripe"` . Added property will be available in template. – dani herrera Apr 23 '13 at 13:31
  • 1
    Also, you can create a custom filter: https://code.djangoproject.com/ticket/3371 – dani herrera Apr 23 '13 at 13:36
  • 1
    http://stackoverflow.com/questions/8000022/django-template-how-to-lookup-a-dictionary-value-with-a-variable – Bartosz Marcinkowski Apr 23 '13 at 13:44
  • "Unfortunately I can't add the field "Fruit_Quality" to the model, because Fruit_Quality is dynamically created, and not meant to be stored. So that is not a solution." try it, not in model definition but in view side. – dani herrera Apr 23 '13 at 16:31
  • I used the custom filter method, work very nicely. I wish the django template language was as flexible as python. I can understand their philosophy, but imagine how many man hours people have spent trying to do things that can't be done, and the effort people made to add custom filters. :) – user1993015 Apr 23 '13 at 21:17

0 Answers0