gpt4 book ai didi

python - 查询集中缺少对象

转载 作者:行者123 更新时间:2023-12-01 05:11:58 25 4
gpt4 key购买 nike

我有一个模型:

class Post(models.Model):
is_active = models.BooleanField()
created = models.DateTimeField()

还有两个 CBV:PostListView 和 PostDetailView。

queryset = Post.objects.filter(is_active=True, created__lt=timezone.now())

在这两种情况下。

问题:每个第二个 PostListView 渲染响应都没有带有 created=datetime.datetime(2014, 5, 29, 13, 40, tzinfo=<UTC>) 的 Post 实例。 PostDetailView 返回 404(每第二个响应!)。没关系,当我尝试在 shell 中重现错误时:

>>> Post.objects.filter(is_active=True, created__lte=timezone.now())
[<Post: 1>, <Post: 2>]
>>> Post.objects.filter(is_active=True, created__lte=timezone.now())
[<Post: 1>, <Post: 2>]
>>> Post.objects.filter(is_active=True, created__lte=timezone.now())
[<Post: 1>, <Post: 2>]
>>> Post.objects.filter(is_active=True, created__lte=timezone.now())
[<Post: 1>, <Post: 2>]

更新:

class PostListView(ListView):
queryset = Post.objects.filter(is_active=True, created__lt=timezone.now())
context_object_name = 'posts'

def get_context_data(self, **kwargs):
context = super(PostListView, self).get_context_data(**kwargs)
context['recommended'] = self.get_queryset().filter(is_recommended=True)[:5]
return context


class PostDetailView(DetailView):
queryset = Post.objects.filter(is_active=True, created__lt=timezone.now())
context_object_name = 'post'

def get_context_data(self, **kwargs):
context = super(PostDetailView, self).get_context_data(**kwargs)
context['recommended'] = self.get_queryset().filter(is_recommended=True)[:5]
return context


print self.get_queryset().query
SELECT `blog_post`.`id`, `blog_post`.`title`, `blog_post`.`slug`, `blog_post`.`meta_description`, `blog_post`.`img`, `blog_post`.`announcement`, `blog_post`.`content`, `blog_post`.`author_id`, `blog_post`.`is_innovation`, `blog_post`.`is_recommended`, `blog_post`.`is_active`, `blog_post`.`created` FROM `blog_post` WHERE (`blog_post`.`created` < 2014-06-04 15:02:44 AND `blog_post`.`is_active` = True ) ORDER BY `blog_post`.`created` DESC

print Post.objects.filter(is_active=True, created__lt=timezone.now()).query SELECT blog_post.id, blog_post.title, blog_post.slug, blog_post.meta_description, blog_post.img, blog_post.announcement, blog_post.content, blog_post.author_id, blog_post.is_innovation, blog_post.is_recommended, blog_post.is_active, blog_post.created FROM blog_post WHERE (blog_post.created < 2014-06-04 15:11:42 AND blog_post.is_active = True ) ORDER BY blog_post.created DESC

在 nginx + Gunicorn + gevent(Ubuntu 服务器,MySQL)上运行。

最佳答案

如果您要对查询集过滤器使用函数调用,则无法将其设置为属性。您必须覆盖 get_queryset

def get_queryset(self):
queryset = super(PostListView, self).get_queryset()
return queryset.filter(is_active=True, created__lt=timezone.now())

原因是 timezone.now() 将始终返回类首次编译时的值。您也许可以使用 .filter(created__lt=timezone.now) 但我还没有尝试过。

关于python - 查询集中缺少对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24040538/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com