Django 中有序、过滤的查询集中的下一个或上一个项目
next or previous item within an ordered, filtered queryset in Django
如何从 post_details(DetailView) 过渡到下一篇文章,以便下一篇和上一篇文章都可用?
vievs.py
class HomeView(ListView):
model = Post
#queryset = Post.objects.filter(status=1)
cats = Category.objects.all()
template_name = 'home.html'
#ordering = ['-post_date']
paginate_by = 6
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
return context
class ArticleDetailView(HitCountDetailView):
model = Post
template_name = 'post_detail.html'
count_hit = True
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = stuff.total_likes()
context["cat_menu"] = cat_menu
context["total_likes"] = total_likes
return context
按日期和 ID 排序
如果您想要基于 DateTimeField
的上一个或下一个项目,您可以使用 .get_previous_by_<i>fieldname</i>(…)
[Django-doc] or .get_next_by_<i>fieldname</i>(…)
[Django-doc]。因此,您可以获得 stuff
的 previous/next 项目:
try:
prev_stuff = stuff<b>.get_previous_by_post_date()</b>
except Stuff.DoesNotExist:
prev_stuff = None
try:
next_stuff = stuff<b>.get_next_by_post_date()</b>
except Stuff.DoesNotExist:
next_stuff = None
如何从 post_details(DetailView) 过渡到下一篇文章,以便下一篇和上一篇文章都可用?
vievs.py
class HomeView(ListView):
model = Post
#queryset = Post.objects.filter(status=1)
cats = Category.objects.all()
template_name = 'home.html'
#ordering = ['-post_date']
paginate_by = 6
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(HomeView, self).get_context_data(*args, **kwargs)
context["cat_menu"] = cat_menu
return context
class ArticleDetailView(HitCountDetailView):
model = Post
template_name = 'post_detail.html'
count_hit = True
def get_context_data(self, *args, **kwargs):
cat_menu = Category.objects.all()
context = super(ArticleDetailView, self).get_context_data(*args, **kwargs)
stuff = get_object_or_404(Post, id=self.kwargs['pk'])
total_likes = stuff.total_likes()
context["cat_menu"] = cat_menu
context["total_likes"] = total_likes
return context
按日期和 ID 排序
如果您想要基于 DateTimeField
的上一个或下一个项目,您可以使用 .get_previous_by_<i>fieldname</i>(…)
[Django-doc] or .get_next_by_<i>fieldname</i>(…)
[Django-doc]。因此,您可以获得 stuff
的 previous/next 项目:
try:
prev_stuff = stuff<b>.get_previous_by_post_date()</b>
except Stuff.DoesNotExist:
prev_stuff = None
try:
next_stuff = stuff<b>.get_next_by_post_date()</b>
except Stuff.DoesNotExist:
next_stuff = None