开发者

Get the latest 5 objects from 2 level deep

I have 3 models

class Category(models.Model):
    name = models.CharField(unique=True, max_length=150)
    ...

class Group(models.Model):
    name = models.CharField(unique=True, max_length=150)
    category = models.ForeignKey(Category)
    ...

class Item(models.Model):
    name = models.CharField(max_length=1开发者_运维问答50)
    group = models.ForeignKey(Group)
    date = models.DateTimeField(editable=False)
    ...

    class Meta:
    ordering = ['-date']

Now I need to get latest 5 items which belongs to the Category in template, so for the groups inside known category its easy

{% for x in category.group_set.all %}
    {{ x.name }} # get the group
    {% for y in x.item_set.all|slice:":5" %}
      {{ y.name }} # get the items from the group
    {% endfor %}
{% endfor %}

Problem is when I have list of categories and don't need groups, just latest 5 items joined which belong to the category. If I use

 {% for category in categories %}
     {% for x in category %} # gives me group again

I hope that I'm explain the problem. I'm lost all day looking for the solution. Thanks


I don't think this is a problem that can be easily solved with template code, because it requires a more complex queryset than those available by default. I would probably solve this problem by adding a method to the Category class:

class Category(models.Model):
    name = models.CharField(unique=True, max_length=150)
    ...

    def latest_items(self):
        return Item.objects.filter(group__category=self)

and then in the template code:

{% for category in categories %}
    {% for item in category.latest_items %} 
        {{ y.name }}
    {% endfor %}
{% endfor %}

Note that you might need to define the Category class after the Item class in this case, and create the ForeignKey relationships to Category with strings.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜