繁体   English   中英

在Django模板中对div排序

[英]Sort divs in django template

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

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

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

我想要模板中的此逻辑:

  • 1)按日期排序所有文章
  • 2)如果最后3条新闻= Small_news =>创建3格的行
  • 3)如果在最后3条新闻中有Big_news =>用Big_news创建行->然后用小新闻创建行(如果big_news之后的所有3条新闻都是small_news)

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

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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM