Skip to content

Commit

Permalink
Merge pull request #259 from aniav/filter-published
Browse files Browse the repository at this point in the history
Introduce __lte=now() instead of isnull=False
  • Loading branch information
aniav committed Feb 13, 2015
2 parents e9fa540 + 1d04f84 commit 789210f
Show file tree
Hide file tree
Showing 6 changed files with 29 additions and 21 deletions.
8 changes: 4 additions & 4 deletions en/django_orm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,9 +101,9 @@ Or maybe we want to see all the posts that contain a word 'title' in the `title`

> **Note** There are two underscore characters (`_`) between `title` and `contains`. Django's ORM uses this syntax to separate field names ("title") and operations or filters ("contains"). If you only use one underscore, you'll get an error like "FieldError: Cannot resolve keyword title_contains".
You can also get a list of all published posts. We do it by filtering all the posts that have `published_date`:

>>> Post.objects.filter(published_date__isnull=False)
You can also get a list of all published posts. We do it by filtering all the posts that have `published_date` set in the past:
>>> from django.utils import timezone
>>> Post.objects.filter(published_date__lte=timezone.now())
[]

Unfortunately, none of our posts are published yet. We can change that! First get an instance of a post we want to publish:
Expand All @@ -116,7 +116,7 @@ And then publish it with our `publish` method!

Now try to get list of published posts again (press the up arrow button 3 times and hit Enter):

>>> Post.objects.filter(published_date__isnull=False)
>>> Post.objects.filter(published_date__lte=timezone.now())
[<Post: Sample title>]

### Ordering objects
Expand Down
8 changes: 5 additions & 3 deletions en/dynamic_data_in_templates/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,16 @@ You should already be familiar with how QuerySets work. We talked about it in [D

So now we are interested in a list of blog posts that are published and sorted by `published_date`, right? We already did that in QuerySets chapter!

Post.objects.filter(published_date__isnull=False).order_by('published_date')
Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')

Now we put this piece of code inside the `blog/views.py` file by adding it to the function `def post_list(request)`:

from django.shortcuts import render
from django.utils import timezone
from .models import Post

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

Please note that we create a *variable* for our QuerySet: `posts`. Treat this as the name of our QuerySet. From now on we can refer to it by this name.
Expand All @@ -48,10 +49,11 @@ In the `render` function we already have parameter with `request` (so everything
So finally our `blog/views.py` file should look like this:

from django.shortcuts import render
from django.utils import timezone
from .models import Post

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

That's it! Time to go back to our template and display this QuerySet!
Expand Down
9 changes: 5 additions & 4 deletions pl/django_orm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,10 @@ A gdybyśmy chciały wyświetlić wszystkie wpisy zawierające słowo 'title' w

> **Uwaga:** Pomiędzy `title` a `contains` znajdują się dwa znaki podkreślenia (`_`). ORM w Django używa takiej składni, aby oddzielić nazwy pól ("title") od operacji lub filtrów ("contains"). Jeśli użyjesz tylko jednego, zobaczysz błąd o treści "FieldError: Cannot resolve keyword title_contains".
Możemy także wyświetlić listę wszystkich opublikowanych wpisów. W tym celu odfiltrujmy wszystkie wpisy, które mają ustawioną datę publikacji (`published_date`):
Możemy także wyświetlić listę wszystkich opublikowanych wpisów. W tym celu odfiltrujmy wszystkie wpisy, które mają ustawioną datę publikacji (`published_date`) w przeszłości:

>>> Post.objects.filter(published_date__isnull=False)
>>> from django.utils import timezone
>>> Post.objects.filter(published_date__lte=timezone.now())
[]


Expand All @@ -134,7 +135,7 @@ A następnie opublikuj go za pomocą metody `publish`!

Teraz spróbujmy jeszcze raz wyświetlić listę opublikowanych wpisów (wciśnij trzykrotnie klawisz ze strzałką do góry, a następnie zatwierdź klawiszem Enter):

>>> Post.objects.filter(published_date__isnull=False)
>>> Post.objects.filter(published_date__lte=timezone.now())
[<Post: Sample title>]


Expand All @@ -155,4 +156,4 @@ Możemy także odwrócić kolejność poprzez dodanie `-` na początku:
Doskonale! Jesteś teraz gotowa na następną część! Zamknij konsolę poleceniem:

>>> exit()
$
$
8 changes: 5 additions & 3 deletions pl/dynamic_data_in_templates/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,17 @@ Powinnaś być już zaznajomiona z zasadą działania obiektów typu QuerySet. R

Więc teraz interesuje nas lista wpisów, które zostały opublikowane i posortowane według daty publikacji (`published_date`), zgadza się? Już to zrobiłyśmy w rozdziale o QuerySetach!

Post.objects.filter(published_date__isnull=False).order_by('published_date')
Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')


Teraz umieśćmy ten kod wewnątrz pliku `blog/views.py` poprzez dodanie go do funkcji `def post_list(request)`:

from django.shortcuts import render
from django.utils import timezone
from .models import Post

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


Expand All @@ -54,10 +55,11 @@ W funkcji `render` mamy już parametr `request` (czyli wszystko to, co odbieramy
Zatem ostatecznie nasz plik `blog/views.py` powinien wyglądać następująco:

from django.shortcuts import render
from django.utils import timezone
from .models import Post

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


Expand Down
9 changes: 5 additions & 4 deletions uk/django_orm/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,10 @@ A QuerySet є, по суті, списком об'єктів заданої Mode

> **Зауваження** Тут використано два знаки підкреслювання (`_`) між `title` і `contains`. Django ORM використовує цей синтаксис щоб відокремити імена полів ("title") і операції або фільтри ("contains"). Якщо ви раптом використаєте одне підкреслювання, то отримаєте помилку на кшталт "FieldError: Cannot resolve keyword title_contains".
Також можна отримати список усіх опублікованих постів. Зробимо це відфільтрувавши усі пости, що мають `published_date`:
Також можна отримати список усіх опублікованих постів. Зробимо це відфільтрувавши усі пости, що мають published_date`: задану в минулому часі

>>> Post.objects.filter(published_date__isnull=False)
>>> from django.utils import timezone
>>> Post.objects.filter(published_date__lte=timezone.now())
[]


Expand All @@ -134,7 +135,7 @@ A QuerySet є, по суті, списком об'єктів заданої Mode

А тепер спробуйте вивести список усіх опублікованих постів знову (натисніть 3 рази кнопку із стрілочкою вверх і після цього - Enter):

>>> Post.objects.filter(published_date__isnull=False)
>>> Post.objects.filter(published_date__lte=timezone.now())
[<Post: Sample title>]


Expand All @@ -155,4 +156,4 @@ QuerySets також дозволяє впорядковувати список
Клас! Тепер ви готові до наступної частини! Щоб закрити командну оболонку, наберіть:

>>> exit()
$
$
8 changes: 5 additions & 3 deletions uk/dynamic_data_in_templates/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,17 @@

Отже, наразі ми зацікавлені у списку опублікованих і відсортованих за параметром `published_date` блог постів, чи не так? Ми вже робили це у розділі QuerySets!

Post.objects.filter(published_date__isnull=False).order_by('published_date')
Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date')


А тепер вставимо цей шматок коду у файл `blog/views.py` додавши його до функції `def post_list(request)`:

from django.shortcuts import render
from django.utils import timezone
from .models import Post

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


Expand All @@ -54,10 +55,11 @@
Отже, врешті-решт наш файл `blog/views.py` матиме наступний вигляд:

from django.shortcuts import render
from django.utils import timezone
from .models import Post

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


Expand Down

0 comments on commit 789210f

Please sign in to comment.