I’m currently doing something like this in my views.py:
def home(request):
ingredients = Ingredience.objects.all()
drinks = Ingredience.objects.filter(category_id=1)
fruits = Ingredience.objects.filter(category_id=2)
etc.
meats = Ingredience.objects.filter(category_id=25)
return render_to_response('home.html', {'ingredients': ingredients, 'drinks': drinks, 'fruits': fruits, 'meats': meats,}, context_instance=RequestContext(request))
And this is my models.py:
from django.db import models
class IngredienceCategory(models.Model):
name = models.CharField(max_length=30)
def __unicode__(self):
return self.name
class Ingredience(models.Model):
name = models.CharField(max_length=30)
category = models.ForeignKey(IngredienceCategory, null=True, blank=True)
def __unicode__(self):
return self.name
class Food(models.Model):
name = models.CharField(max_length=30)
ingredients = models.ManyToManyField(Ingredience)
def __unicode__(self):
return self.name
Is there some trick in django to generate the template objects (i.e. drinks, fruits, meats) dynamically? I don’t even know where to start but I thought doing something like this: loop through all ingredients objects and return dictionary which would hold items grouped by category (as in the first example).
There are 2 problems I’m trying to solve with this:
- The code for each category object is almost the same so there is a
lot of redundancy. - I have to update views.py every time I add new
category to the database.
EDIT: In my template I need to be able to access each object (i.e. drinks, fruits, meats etc.) by its own variable (e.g. {{ drinks }}.
Okay, based on your comments, you want to be able to access
fruits,meats, etc in your template. Here is one possible solution that’s neither incredibly pythonic nor efficient, but that’s just to make it easier to understand:Then you could access it as
fruits,meats, etc. Does Django have something for what you’re looking for exactly? Not as far as I know, it’s quite a rare use-case – but maybe some others could provide an answer to that. Essentially what you’re trying to achieve is some clever maneuvering of a context dictionary object so that the categories become the keys. If that’s the case, you might find some use also looking at this SO question.Update: Just to clarify what I’m doing in the code above: I create a dictionary called
context, and then proceed to loop through all the ingredients. For every ingredient, I add a dictionary entry for the category name, containing an array with the Ingredient. If the name is already in the context dictionary, then it just appends this Ingredient. It does this until all the ingredients have been added to an array accessible by the name of the category it is in.