【问题标题】:How to change the queryset returned based on the URL如何更改基于 URL 返回的查询集
【发布时间】:2020-02-11 03:30:46
【问题描述】:

我正在尝试制作一个教育网站并制作了一个类别系统。每个类别都有一个 URL,我需要根据我所在的 URL 更改返回的查询集。例如,如果我在“localhost:8000/posts/category/3”上,我希望我的查询集返回为:

Post.objects.filter(category=3).order_by('-date_posted')

等等,取决于 URL。

我不知道从哪里开始。

返回查询集的基于类的视图:

class CatPostListView(ListView):
    model = Post
    template_name = 'blog/science.html' #This is when you click a profile in a post, it takes you to his posts only
    context_object_name = 'posts'
    paginate_by = 15

    def get_queryset(self):
        return Post.objects.filter(category=2).order_by('-date_posted')

urls.py(只包含必要的部分):

urlpatterns = [
    path('post/category/<int:pk>/', CatPostListView.as_view(), name='category')
]

以防万一models.py:

class Category(models.Model):
    name = models.CharField(max_length=200)
    slug = models.SlugField()
    parent = models.ForeignKey('self', blank=True, null=True, related_name='children', on_delete=models.SET_NULL)

    class Meta:
        # enforcing that there can not be two categories under a parent with same slug

        # __str__ method elaborated later in post.  use __unicode__ in place of

        # __str__ if you are using python 2

        unique_together = ('slug', 'parent',)
        verbose_name_plural = "categories"


    def __str__(self):
        return self.name

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.SET_NULL)
    display = models.TextField(max_length=250)
    date_posted = models.DateTimeField(default=timezone.now)#DON'T USE () HERE Just auto_now_ will show the date of the current day
    author = models.ForeignKey(User, on_delete=models.CASCADE)#No () #This deletes the posts when the user is deleted


    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post-detail', kwargs={'pk': self.pk})

如果我使用我在此处发布的视图,那将无法正常工作。我需要一种方法从 url 中获取 pk 并将其放入视图中。

【问题讨论】:

    标签: django python-3.x


    【解决方案1】:

    您可以从 URL 中获取值:

    return Post.objects.filter(category=self.kwargs['pk']).order_by('-date_posted')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2021-06-18
      • 2013-11-22
      • 1970-01-01
      相关资源
      最近更新 更多