开发者

Queryset comparision inside a template, maybe using custom version of {% ifchanged %} tag

I have two models as follows:

class Tag(models.Model):
    # ...

class Paragraph(models.Model):
    tags = models.ManyToManyField(Tag)
    # ...

Inside a template I'm iterating through queryset of Paragraph objects to display them, using {% 开发者_开发问答for %} tag. I also need to display related tags, but only if they are diffrent from previous iteration. This means that if I'm rendering list of 5 paragraphs, and the first four of them have identical tags, but the fifth one have diffrent tags, I want to display the tags only by the first and the fifth paragraph.

I tried to use {% ifchanged %} build-in tag, but as I figured out, I can't use {% ifchanged paragraph.tags.all %} because it will always return True, even if paragraph.tags.all contains the same elements.

So I think of witing a custom template tag {% iftagschanged %} at the base of {% ifchanged %} tag, but using diffrent method of comparision, that compares querysets content insted of querysets themselves, which would always not match. Problem is, that as I looked at {% ifchanged %} tag in django source, it looks a bit complicated to me, and I can't find out, how to change it to work properly in my case.

So I'll be thankfull for advice or maybe an idea of any diffrent solution.


Create a custom method on the Paragraph model that returns its associated tags in a datastructure that can be easily compared - say, a set - and use that as the argument to ifchanged.

class Paragraph(models.Model):
    def tags_as_set(self):
        return set(t.tag for t in self.tags.all())


{% ifchanged paragraph.tags_as_set %}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜