I am creating little blog app. I want to return post, and (my problem), previous and next posts, so I can display them together with post. My current decision is very bad, because not only I load all Post objects, but also convert QuerySet to list. Here is a snippet from 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, 'ppos开发者_如何学Ct': ppost, 'npost': npost},
context_instance=RequestContext(request))
And here is 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']
I would appreciate any architectural ideas, how to implement this case. Any ideas actually :). Thank you in advance
You don't have to implement fetching the next and previous instances yourself, it's already builtin: http://docs.djangoproject.com/en/1.3/ref/models/instances/#django.db.models.Model.get_previous_by_FOO
If you want to tweak this a bit, for example to get the neighboring instances for non-date fields, see this thread on django users
With these model methods you can create a pager in your template like this:
<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>
精彩评论