Django - 我如何在分页中包含几个元素

时间:2016-06-25 18:30:34

标签: python django pagination

这是我在django的第一个项目,我一直在关注几个不同的教程,其中大部分非常有用。我已经制作了一个非常简单的博客作为我的第一个应用程序,现在我将其扩展到教程向我展示的范围之外。也就是说,我添加了每个帖子都可以属于的新模型,类别。模型本身和所有相关的东西都有效。我现在唯一遇到的问题是解析网址。我使用分页来正常列出帖子,但我想添加其他可选元素,即类别。因此,在浏览列表时,我不仅可以选择site.com/posts/?page=2,还可以使用类似site.com/posts/?cat=news&page=2

的选项

models.py

# Model for blog post category
class Category(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(unique=True)
    description = models.TextField()

    class Meta:
        verbose_name_plural = "Categories"

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug": self.slug})
# Model for blog post
class Post(models.Model):
    title = models.CharField(max_length=120)
    slug = models.SlugField(unique=True)
    category = models.ManyToManyField(Category, blank=True, through='CategoryToPost')
    content = models.TextField()
    image = FilerImageField(null=True, blank=True, related_name="post_image")
    created = models.DateTimeField(auto_now=False, auto_now_add=True)
    published = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)

    def __str__(self):
        return self.title

    def Category(self):
        return self.category.all()

    def get_absolute_url(self):
        return reverse("posts:detail", kwargs={"slug": self.slug})
# Model for assigning post to a category
class CategoryToPost(models.Model):
    post = models.ForeignKey(Post)
    category = models.ForeignKey(Category)

urls.py

from .views import (
    post_list,
    post_detail
    )

urlpatterns = [
    url(r'^$', post_list),
    url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
]

关于网址的注意事项,项目urls.py中的行是url(r'^posts/', include("posts.urls", namespace='posts')),

views.py

def post_detail(request, slug):

    instance = get_object_or_404(Post, slug=slug)

    context = {
        "title": instance.title,
        "instance": instance,
    }

    return render(request, "post_single.html", context)

def post_list(request):

    queryset_list = Post.objects.all().order_by("-published")
    paginator = Paginator(queryset_list, 5)

    page = request.GET.get('page')
    try:
        queryset = paginator.page(page)
    except PageNotAnInteger:
        queryset = paginator.page(1)
    except EmptyPage:
        queryset = paginator.page(paginator.num_pages)

    context = {
        "title": "Post List",
        "object_list": queryset,
    }

    return render(request, "post_list.html", context)

我知道我需要在post_list中添加这个内容,但说实话,我甚至不知道从哪里开始,django分页文档在这方面不是很清楚。

1 个答案:

答案 0 :(得分:1)

<强> views.py

...
queryset_list = Post.objects.all().order_by("-published")
if request.GET.get('cat'):
    queryset_list = queryset_list.filter(category__slug=request.GET.get('cat'))
...

<强> urls.py

from .views import (
    post_list,
    post_detail
    )

urlpatterns = [
    # Add name to url so that we can use it with reverse
    url(r'^$', post_list, name='list'),
    url(r'^(?P<slug>[\w-]+)/$', post_detail, name='detail'),
]

<强> models.py

class Category(models.Model):
    ...
    def get_absolute_url(self):
        return reverse('posts:list')+'?cat='+self.slug