【发布时间】:2012-07-13 10:30:39
【问题描述】:
我在一个应用和 1 个视图中有 2 个模型。我目前从 1 个模型中提取信息非常好。但是我希望从同一个应用程序中提取另一个模型并将它们都输出到同一个页面。
该页面的想法是它是一个新闻中心,因此它可以浏览不同类型的新闻帖子(来自一个模型)和来自另一个模型的不同类型的帖子。
我对 Django 还很陌生,所以放轻松! :) 无论如何这里是代码:
//视图
def news_home(request):
page_context = details(request, path="news-hub", only_context=True)
recent_posts = NewsPost.objects.filter(live=True, case_study=False).order_by("-posted")[:5]
recent_posts_pages = Paginator(recent_posts, 100)
current_page = request.GET.get("page", 1)
this_page = recent_posts_pages.page(current_page)
notes = BriefingNote.objects.filter(live=True).order_by("-posted")
news_categories = NewsCategory.objects.all()
news_context = {
"recent_posts": this_page.object_list,
"news_categories": news_categories,
"pages": recent_posts_pages,
"note": notes,
}
context = dict(page_context)
context.update(news_context)
return render_to_response('news_hub_REDESIGN.html', context, context_instance=RequestContext(request))
//模型1
class BriefingNote(models.Model):
title = models.CharField(max_length=300)
thumbnail = models.ImageField(upload_to='images/briefing_notes', blank=True)
file = models.FileField(upload_to='files/briefing_notes')
live = models.BooleanField(help_text="The post will only show on the frontend if the 'live' box is checked")
categories = models.ManyToManyField("NewsCategory")
# Dates
posted = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __unicode__(self):
return u"%s" % self.title
//模型2
class NewsPost(models.Model):
title = models.CharField(max_length=400)
slug = models.SlugField(help_text="This will form the URL of the post")
summary = models.TextField(help_text="To be used on the listings pages. Any formatting here will be ignored on the listings page.")
post = models.TextField(blank=True)
#TO BE REMOVED????
thumbnail = models.ImageField(help_text="To be displayed on listings pages", upload_to="images/news", blank=True)
remove_thumbnail = models.BooleanField()
我在前端输出内容是这样的:
{% for post in recent_posts %}
<div class='news_first'>
<img class="news_thumb" src="/media/{% if post.article_type %}{{post.article_type.image}}{% endif %}{% if post.news_type %}{{post.news_type.image}}{% endif%}" alt="">
<h3><a href='{{post.get_absolute_url}}'>{% if post.article_type.title %}{{post.title}}{% endif %} <span>{{post.posted|date:"d/m/y"}}</span></a></h3>
<p class='news_summary'>
{% if post.thumbnail %}<a href='{{post.get_absolute_url}}'><img src='{% thumbnail post.thumbnail 120x100 crop upscale %}' alt='{{post.title}}' class='news_thumbnail'/></a>{% endif %}{{post.summary|striptags}} <a href='{{post.get_absolute_url}}'>Read full story »</a>
</p>
<div class='clearboth'></div>
</div>
{% endfor %}
我在想也许我可以在同一个 forloop 中输出它们,但是它们需要按 -posted 排序。所以我虽然这可能会把事情搞砸。
如果您需要更多信息,请告诉我。
提前致谢。
【问题讨论】:
-
这真的是我需要做的吗?在那篇文章中,他们跑题了,似乎他们在最终结果中做了一些不同的事情?
-
我在 NewsPost 中没有看到 DateTimeField,您打算如何按发布日期排序?
-
由于模型相当大,我没有发布所有模型字段。
-
那个帖子没用?谁能帮我吗?快把我逼疯了!
标签: django django-models django-views