在Django模板中对div排序

时间:2018-08-13 21:47:30

标签: django django-templates django-template-filters

我是Django的新手,请帮助解决我的问题。

class Article(models.Model):
articlecategory = models.ForeignKey(ArticleCategory)

Articlecategory可以按Big_news(连续1个新闻)或Small_news(连续3个新闻)

我想要模板中的这种逻辑:

  • 1)按日期对所有文章进行排序
  • 2)如果最后3条新闻= Small_news =>创建 3 div的行
  • 3)如果最近3条新闻中有Big_news =>创建行 使用big_news->,然后创建包含小新闻的行(如果big_news之后的所有3条新闻均为small_news)

如何在Django中获取此信息(第3段)?

1 个答案:

答案 0 :(得分:0)

您应该在您的视图中处理此逻辑。它不属于您的模板。

class ArticleRowViewModel:
    def __init__(self, articles):
        self.articles = articles

    def is_big_news(self):
        return len(self.articles) == 1

articles = Article.objects.all().order_by('-date')
previous_articles = []
view_models = []
for article in articles:
    if article.big_news:
        # TODO: I don't know if this is right.
        # Your business logic didn't cover it. I'm treating it if there
        # any small news articles, that they should appear as such before
        # the current big `article` in the loop.
        if previous_articles:
            view_models.append(ArticleRowViewModel(previous_articles))
            previous_articles = []
        view_models.append(ArticleRowViewModel([article]))
    else:
        previous_articles.append(article)
        # Check if we have 3 small articles.
        if len(previous_articles) == 3:
            view_models.append(ArticleRowViewModel(previous_articles))
            previous_articles = []  
render_or_something(view_models)