我想建立一个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)
答案 0 :(得分:2)
使用
def get_queryset(self):
return Post.objects.filter(published=True)
代替
def get_queryset(self):
return Post.objects.filter('published'==True).all()
可以找到参考文献here。