#Django_ORM #filters
Subquery
Django allows using SQL subqueries. Let’s start with something simple, We have a UserParent model which has OnetoOne relation with auth user. We will find all the UserParent which have a UserParent.
from django.db.models import Subquery
users = User.objects.all()
UserParent.objects.filter(user_id__in=Subquery(users.values('id')))
#source
https://books.agiliq.com/projects/django-orm-cookbook/en/latest/subquery.html
Subquery
Django allows using SQL subqueries. Let’s start with something simple, We have a UserParent model which has OnetoOne relation with auth user. We will find all the UserParent which have a UserParent.
from django.db.models import Subquery
users = User.objects.all()
UserParent.objects.filter(user_id__in=Subquery(users.values('id')))
#source
https://books.agiliq.com/projects/django-orm-cookbook/en/latest/subquery.html
👍1
Instead of this
#Source "Python Tricks" by Dan Bader
names = ['Alice', 'Bob', 'Dilbert']
Use:>>> names = [
... 'Alice',
... 'Bob',
... 'Dilbert',
... ]
That way there’s one item per line, making it perfectly clear which one was added, removed, or modified when you view a diff in your source control system. It’s a small change but helpful to avoid silly mistakes. It also easier for your teammates to review your code changes.#Source "Python Tricks" by Dan Bader
Context Managers
#not_secure
#Secure
#not_secure
f = open('hello.txt', 'w')
f.write('hello, world')
f.close()
This implementation won’t guarantee the file is closed if there’s an exception during the f.write() call#Secure
with open('hello.txt', 'w') as f:
f.write('hello, world!')
Behind the scenes context manager is implementing the following:f = open('hello.txt', 'w')
try:
f.write('hello, world')
finally:
f.close()
#Source "Python Tricks" by Dan BaderSingle Leading Underscore:
!!!Note: if you import all the names from the module, Python will not import names with a leading underscore(unless the module defines an all list that overrides this behavior)
#Source "Python Tricks" by Dan Bader
_var
is a hint to tell another programmer that a variable or method starting with a single underscore is intended for internal use. !!!Note: if you import all the names from the module, Python will not import names with a leading underscore(unless the module defines an all list that overrides this behavior)
#Source "Python Tricks" by Dan Bader
#functions
Function notes
Python adds an implicit return None statement to the end of any function. Therefore, if a function doesn’t specify a return value, it re- turns None by default. you can replace return None statements with bare
#Source "Python Tricks" by Dan Bader
Function notes
Python adds an implicit return None statement to the end of any function. Therefore, if a function doesn’t specify a return value, it re- turns None by default. you can replace return None statements with bare
#Source "Python Tricks" by Dan Bader