Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
development:python:django:models [2020/07/21 11:38] kalenpw created |
development:python:django:models [2021/06/29 15:18] (current) kalenpw |
||
---|---|---|---|
Line 2: | Line 2: | ||
Methods, tips, and tricks for working with Django Models | Methods, tips, and tricks for working with Django Models | ||
+ | ---- | ||
===== Query ===== | ===== Query ===== | ||
Line 8: | Line 9: | ||
# all posts | # all posts | ||
- | Post.objects.all() | + | posts = Post.objects.all() |
# filtered by field | # filtered by field | ||
- | Post.objects.filter(pub_date__year=2020) # can chain additional .filter() | + | posts = Post.objects.filter(pub_date__year=2020) # can chain additional .filter() |
+ | # queries are done lazily and won't be ran until necessary | ||
+ | posts = posts.filter(pub_date__month=12) | ||
+ | print(posts) # now the query actually runs | ||
</ | </ | ||
+ | |||
+ | %%__%% filters for queries | ||
+ | <code python> | ||
+ | # use a __ (dunder) after a field name to access different forms of it ie | ||
+ | posts = Post.objects.filter(title=" | ||
+ | posts = Post.objects.filter(title__contains=" | ||
+ | posts = Post.objects.filter(title__startswith=" | ||
+ | posts = Post.objects.filter(pub_date__year=2020) # can also use month, day | ||
+ | </ | ||
+ | |||
+ | ---- |