如何使用objects.filter()选择仅布尔True帖子

时间:2019-04-16 05:13:57

标签: python django

我想建立一个Post模型的查询集,该查询集仅过滤published=True视图中的Public

我尝试了以下方法:

return Post.objects.filter('published'==True).all()

views.py

class PublicList(ListView):
    template_name = 'publish.html'
    context_object_name = 'items'
    model = Post

    def get_queryset(self):
        return Post.objects.filter('published'==True).all()

models.py

class Post(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=100)
    description = models.TextField()
    created_on = models.DateTimeField(default=timezone.now)
    published = models.BooleanField(default=False)

    def publish(self):
       self.published=True
        self.save()

    def unpublish(self):
        self.published=False
        self.save()

    def __str__(self):
        return self.title

回溯错误:

 File "C:\Users\AngryBuLLz\Desktop\Django\prac_18\firstapp\views.py" in    get_queryset
82.         return Post.objects.filter('published'==True).all()

 File "C:\Users\AngryBuLLz\AppData\Local\conda\conda\envs\madeenv\lib\site-packages\django\db\models\manager.py" in manager_method
82.                 return getattr(self.get_queryset(), name)(*args, **kwargs)

1 个答案:

答案 0 :(得分:2)

使用

def get_queryset(self):
    return Post.objects.filter(published=True) 

代替

def get_queryset(self):
    return Post.objects.filter('published'==True).all()

可以找到参考文献here