我是Django的新手,请帮助解决我的问题。
class Article(models.Model):
articlecategory = models.ForeignKey(ArticleCategory)
Articlecategory可以按Big_news(连续1个新闻)或Small_news(连续3个新闻)
我想要模板中的这种逻辑:
如何在Django中获取此信息(第3段)?
答案 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)