Filter objects in DJANGO - published_date__lte

Asked

Viewed 216 times

0

I’m following a tutorial for modeling a BLOG through the DJANGO . In one of the processes, I create an object with the site posts and order them through the publication date:

def post_list(request):
    posts =  Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')
    return render(request, 'post/post_list.html',{'posts' : posts})

I know through the shell that I own at least one object, because:

Post.objects.all()
<QuerySet [<Post: Post1>, <Post: Objeto1 - Postagem>]>

But when I seek to verify the object that returns through the filter application appears:

Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') 
<QuerySet []>

Can anyone explain to me what the parameter means published_date__lte and why is not returning the object?

Maybe, I’m not sure, I’m filtering all posts now (timezone.now()) and so does not filter my post. Anyway, I wish someone could explain me better this filter.

Sincerely yours.

2 answers

1

Maybe it’s the fact that you didn’t publish the posts you created in the shell. Then you can do the following:

post = Post.objects.get(<campo_Model> = <valor_atribuido_na_criacao">) -> Here you take an instance of the post you created from a field that is characteristic of it

post.publish() -> Here Cvoce publishes the post itself, assuming its function to publish on its model is Publish()

1


lte in Django you mean "Less than or Equal" that is, less than or equal <=. In case you are filtering the posts whose publication date published_date are less than or equal to the current date and time now().

This means that the query will not return posts that are scheduled to be published in the future (published_date > now()), or drafts which have not yet been published (published_date NULL).

Check through the shell in your post the field published_date how it is filled, to solve the mystery:

[p.published_date for p in Post.objects.all()]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.