Django博客应用程序架构问题

时间:2011-04-07 21:59:13

标签: python django django-views

我正在创建一个小博客应用。我想回复帖子,(我的问题),上一篇和下一篇文章,所以我可以和帖子一起显示它们。我当前的决定非常糟糕,因为我不仅加载所有Post对象,还将QuerySet转换为list。这是来自views.py的片段:

def post(request, url):
        try:
            post = Post.objects.get(slug = url)
        except Post.DoesNotExist:
            raise Http404()
        posts = Post.objects.all().order_by('-date')
        index = list(posts).index(post)
        if index > 0:
            ppost = posts[index - 1] #previuos post
        else:
            ppost = None
        if index < len(posts):
            npost = posts[index + 1] #next post
        else:
            npost = None
        if not post.visible:
            raise Http404()
        return render_to_response('post.html',
                                  {'post': post, 'ppost': ppost, 'npost': npost},
                                  context_instance=RequestContext(request))

这是models.py:

class Post(models.Model):
    slug = models.SlugField(unique=True)
    subject = models.CharField(max_length=150)
    abstract = models.CharField(max_length=300)
    content = models.TextField()
    author = models.ForeignKey(User)
    date = models.DateTimeField(auto_now_add=True)
    visible = models.BooleanField(default=False)
    tags = models.ManyToManyField(Tag, blank = True, null = True)

    def save(self, *args, **kwargs):
        self.abstract = self.content[:297] + "..."
        self.slug = slugify(self.subject)
        super(Post, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.subject

    class Meta:
        ordering = ['-date']

我很欣赏任何建筑理念,如何实施这个案例。任何想法实际上:)。提前谢谢

1 个答案:

答案 0 :(得分:2)

您不必自己实现获取下一个和上一个实例,它已经内置:http://docs.djangoproject.com/en/1.3/ref/models/instances/#django.db.models.Model.get_previous_by_FOO

如果您想稍微调整一下,例如获取非日期字段的相邻实例,请参阅this thread on django users

使用这些模型方法,您可以在模板中创建一个寻呼机,如下所示:

<div id="pager">
    {% if object.get_prev_by_title  %}
        <a class="prev" href="{{ object.get_prev_by_title.get_absolute_url }}">
{{ object.get_prev_by_title }}</a>
    {% endif %}
    {% if object.get_next_by_title  %}
        <a class="next" href="{{ object.get_next_by_title.get_absolute_url }}">
{{ object.get_next_by_title }}</a>
    {% endif %}
</div>