简体   繁体   中英

Django CBV queryset issue

this is my model

class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=256)
text = models.TextField()
create_date = models.DateTimeField(auto_now_add=True, auto_now=False)
published_date = models.DateTimeField(blank=True, null=True)

def __str__(self):
    return f'{self.author} --> {self.title}'

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

def publish(self):
    self.published_date = timezone.now()
    self.save()

def unpublish(self):
    self.published_date = None
    self.save()

and i registered it on Django admin. i have created two post on Django admin, the new post when i publish it and hit now and refresh the page, it won't show this post:

this is admin code:

from django.contrib import admin
from .models import Post, Comment

@admin.register(Post, Comment)
class PostModelAdmin(admin.ModelAdmin):
    pass

this is the view:

class PostListView(ListView):
queryset = Post.objects.filter(published_date__lte=timezone.now())
print('query0: ', queryset)

def get_queryset(self):
    queryset = super().get_queryset()
    print('query1: ', queryset)
    print('query2:', self.queryset)
    print('query3: ', Post.objects.filter(published_date__lte=timezone.now()))
    return Post.objects.filter(published_date__lte=timezone.now())

在此处输入图像描述

As you can see result of query1, query2 is different with query3.

I think this is a bug, if it's not please light me up.

it's been answered by Iain Shelvington in a comment:

The class attribute queryset defined in PostListView is created once when your app starts, it will always filter using the value of timezone.now() at the time when your app started. To test this, try restarting your app after publishing and see if the result changes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM