-1

我目前正在我的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))

这是我的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

django 中是否有一些技巧可以动态生成模板对象(即饮料、水果、肉类)?我什至不知道从哪里开始,但我想这样做:遍历所有成分对象并返回字典,该字典将保存按类别分组的项目(如第一个示例中所示)。

我试图用这个解决两个问题:

  1. 每个类别对象的代码几乎相同,因此有很多冗余。
  2. 每次向数据库添加新类别时,我都必须更新 views.py。

编辑:在我的模板中,我需要能够通过自己的变量(例如{{饮料}}访问每个对象(即饮料、水果、肉类等)。

4

1 回答 1

1

好的,根据您的评论,您希望能够访问模板中的fruits,meats等。这是一种可能的解决方案,它既不是令人难以置信的 Pythonic 也不是高效的,但这只是为了让它更容易理解:

ingredients = Ingredience.objects.all()
context = {}
for i in ingredients:
    context[i.category.name + 's'] = context.get(i.category.name + 's', []) + [i]
return render_to_response('home.html', context, context_instance=RequestContext(request))

然后你可以访问它fruitsmeats等。Django 是否有你正在寻找的东西?据我所知,这是一个非常罕见的用例 - 但也许其他一些人可以提供答案。本质上,您要实现的是对上下文字典对象的一些巧妙操作,以便类别成为键。如果是这种情况,您可能会在查看这个 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.

于 2012-07-08T10:16:19.743 回答