Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Spaces or Tabs
Generally, spaces are the preferred indentation means but if you find some Python scripts already using the tabs, you should go on doing indentation with tabs. Otherwise, you should change the indentation of all the expressions in your script with spaces.
Note that Python 3 doesn't allow mixing tabs and spaces for indentation. That's why you should choose one of the two and stick with it!
Generally, spaces are the preferred indentation means but if you find some Python scripts already using the tabs, you should go on doing indentation with tabs. Otherwise, you should change the indentation of all the expressions in your script with spaces.
Note that Python 3 doesn't allow mixing tabs and spaces for indentation. That's why you should choose one of the two and stick with it!
Code Should have line length of 79 characters
Comments should have 72 characters of line length.
Comments should have 72 characters of line length.
In Python scripts, top-level function and classes are separated by two blank lines. Method definitions inside classes should be separated by one blank line.
Know when to be inconsistent – sometimes the style guide just doesn’t apply. When in doubt, use your best judgment. Look at other examples and decide what looks best. And don’t hesitate to ask!
знайте, когда нужно быть непоследовательным - иногда руководство по стилю просто неприменимо. В случае сомнений используйте здравый смысл.
Посмотрите другие примеры и решите, что выглядит лучше всего. И не стесняйтесь спрашивать!
Andrei Boyanov SSE
знайте, когда нужно быть непоследовательным - иногда руководство по стилю просто неприменимо. В случае сомнений используйте здравый смысл.
Посмотрите другие примеры и решите, что выглядит лучше всего. И не стесняйтесь спрашивать!
Andrei Boyanov SSE
If you want to change your last commit message that is not pushed yet:
git commit --amend -m "New and correct message"
#Django_ORM #filters
OR in filters:
1) queryset = User.objects.filter( first_name__startswith='R') | User.objects.filter(last_name__startswith='D')
2)qs = User.objects.filter(Q(first_name__startswith='R')|Q(last_name__startswith='D'))
In both cases SQL query will be the same
OR in filters:
1) queryset = User.objects.filter( first_name__startswith='R') | User.objects.filter(last_name__startswith='D')
2)qs = User.objects.filter(Q(first_name__startswith='R')|Q(last_name__startswith='D'))
In both cases SQL query will be the same
#Django_ORM #filters
AND in filters:
1) queryset = User.objects.filter( first_name__startswith='R') and User.objects.filter(last_name__startswith='D')
2) queryset_1 & queryset_2
3)filter(Q(<condition_1>) & Q(<condition_2>))
AND in filters:
1) queryset = User.objects.filter( first_name__startswith='R') and User.objects.filter(last_name__startswith='D')
2) queryset_1 & queryset_2
3)filter(Q(<condition_1>) & Q(<condition_2>))
#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
#Django_ORM #filters
F
F is used to filter fields of the same model:
User.objects.filter(last_name=F("first_name"))
F
F is used to filter fields of the same model:
User.objects.filter(last_name=F("first_name"))
#Django_ORM #filters
Select_related, prefetch_related
class ModelA(models.Model):
pass
class ModelB(models.Model):
a = ForeignKey(ModelA)
ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship
Select_related, prefetch_related
class ModelA(models.Model):
pass
class ModelB(models.Model):
a = ForeignKey(ModelA)
ModelB.objects.select_related('a').all() # Forward ForeignKey relationship
ModelA.objects.prefetch_related('modelb_set').all() # Reverse ForeignKey relationship
#Django_ORM #filters
Find Nth record from the query by using slice operator except using first() and last()
e.g
"auth_user"."password",
"auth_user"."last_login",
"auth_user"."is_superuser",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."date_joined"
FROM "auth_user"
ORDER BY "auth_user"."last_login" DESC
LIMIT 1
OFFSET 2
Find Nth record from the query by using slice operator except using first() and last()
e.g
user = User.objects.order_by('-last_login')
[2] // Second Highest record w.r.t 'last_login'
Sql query will look like this:
SELECT
"auth_user"."id","auth_user"."password",
"auth_user"."last_login",
"auth_user"."is_superuser",
"auth_user"."username",
"auth_user"."first_name",
"auth_user"."last_name",
"auth_user"."email",
"auth_user"."is_staff",
"auth_user"."is_active",
"auth_user"."date_joined"
FROM "auth_user"
ORDER BY "auth_user"."last_login" DESC
LIMIT 1
OFFSET 2
#Django_ORM
Make model save only one object
`class Origin(models.Model):
name = models.CharField(max_length=100)
def save(self, *args, **kwargs):
if self.class.objects.count():
self.pk = self.class.objects.first().pk
super().save(*args, **kwargs)`
Make model save only one object
`class Origin(models.Model):
name = models.CharField(max_length=100)
def save(self, *args, **kwargs):
if self.class.objects.count():
self.pk = self.class.objects.first().pk
super().save(*args, **kwargs)`
#Django_ORM #Models
Signals vs Overriding .save
—If your fields depend on a model you control, override .save
—If your fields depend on a model from a 3rd party app, which you do no control, use signals.
Signals vs Overriding .save
—If your fields depend on a model you control, override .save
—If your fields depend on a model from a 3rd party app, which you do no control, use signals.
#Django_ORM #ordering
Order queryset by case insensitive manner
Order queryset by case insensitive manner
User.objects.all().order_by(Lower('username'))