【问题标题】:Django - filter posts by author using a string pk?Django - 使用字符串 pk 按作者过滤帖子?
【发布时间】:2021-05-31 21:36:43
【问题描述】:

我正在建立一个博客,并试图让用户能够查看单个作者的帖子。到目前为止,我已经尝试了不同的过滤器来返回一个有效的视图。这是我得到的最接近的(我认为),但该站点返回为空。有谁知道我错过了什么?

我的models.py

class Author(models.Model):
    user = models.OneToOneField(User,on_delete=models.CASCADE)
    username = user.name
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    
    def get_absolute_url(self):
        return reverse("author", args=[str(self.id)])
    
    def __str__(self):
        return self.user.username

class Post(models.Model):
    author = models.ForeignKey(Author, related_name="user_name",on_delete=models.CASCADE)
    title = models.CharField(max_length=250)
    text = models.TextField()
    created_date = models.DateTimeField(default=timezone.now)
    published_date = models.DateField(blank=True,null=True)

我的view.py

class PostListAuthor(ListView):
    model = Post, Author
    paginate_by = 5
    context_object_name = 'author_posts'
    template_name="blog/post_author_list.html" 
    
    def get_queryset(self):
        return Post.objects.filter(author = Author.username, published_date__lte=timezone.now()).order_by("-published_date")

我的 urls.py 有这个:

path("author/<str:pk>",views.PostListAuthor.as_view(),name="author"),

【问题讨论】:

    标签: django filter author


    【解决方案1】:

    感谢 Ashraful Islam。我被 get_absolute_url 搞混了,你的解决方案让我明白了。

    顺便说一句,我在尝试您的解决方案时遇到了一个错误,但我设法像这样修复了我的代码。现在就像一个魅力。

    urls.py

    path("author/<int:pk>/",views.PostListAuthor.as_view(),name="author"),
    

    views.py

    def get_queryset(self):
            author_id = self.kwargs['pk']
            return Post.objects.filter(author = author_id, published_date__lte=timezone.now()).order_by("-published_date")
    

    models.py

    def get_absolute_url(self):
            return reverse("author", kwargs={'pk':self.pk})
    

    【讨论】:

      【解决方案2】:
      path("author/<int:author_id>/",views.PostListAuthor.as_view(),name="author"),
      

      def get_queryset(self):
          author_id = self.kwargs['author_id']
          return Post.objects.filter(author=int(author_id)).order_by("-published_date")
      

      【讨论】:

        猜你喜欢
        • 2014-01-06
        • 2016-01-10
        • 1970-01-01
        • 2012-07-30
        • 1970-01-01
        • 1970-01-01
        • 2019-09-27
        • 2021-06-06
        • 1970-01-01
        相关资源
        最近更新 更多