0

Here is scenario:

I want to publish one item per day. Sometimes I will add more than one item and set them on different pub_date on admin site. By setting queryset like this item.objects.exclude(pub_date__gt=timezone.now().date()), this will prevent the items on future publish date from publishing. However, I do not get my expected result. P.S. I get my expected result on python manage.py shell and if restart my server--gunicorn manually, the items are published.

Maybe it is related to my server Upstart script, here it is,

start on runlevel [2345]
stop on runlevel [!2345]

respawn
setuid myid
setgid www-data
chdir /home/myid/my_repo_dir/my_proj_dir

exec /home/myid/.virtualenvs/my_proj_env/bin/gunicorn --workers 3 --bind unix:/home/my_id/my_repo_dir/my_proj_dir/project.sock config.wsgi:application$

Here is the view:

class HomeView(ListView):

    queryset = Item.objects.exclude(pub_date__gt=timezone.now().date())
    template_name = 'home.html'
    context_object_name = 'items'

What I cannot understand is that the same code in view and in python manage.py shell produces different results.

sac7e
  • 91
  • 1
  • 10

3 Answers3

1

Override get_queryset, so that the queryset is evaluated each time the view runs.

class HomeView(ListView):
    def get_queryset(self) :
        return Item.objects.exclude(pub_date__gt=timezone.now().date())

Currently, you have set queryset. This causes the queryset to be fetched once when the server starts and the view is loaded. It does not change until the server is restarted.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
0

I suggest you switch from using upstart to gunicorn+supervisor that way it's easier for you to restart your django applications. Also it'll be helpful if you could add more snippets as to how you implemented your queryset.

0

In certain situations (specifically ModelField default values), the .now().date() is evaluated at server start, not at time of calling the method. In that situation, you remove the parenthesis.

This would explain why it works in your shell (because your shell is always todays date).

Try removing the parenthesis from item.objects.exclude(pub_date__gt=timezone.now().date()) to make it item.objects.exclude(pub_date__gt=timezone.now.date).

Community
  • 1
  • 1
knelson
  • 126
  • 1
  • 6
  • Removing the parentheses from `date()` would work for a default value, but doesn't work in this case where it is an argument to filter a queryset. – Alasdair Feb 09 '16 at 18:23