Tech C**P
How to replace multiple characters in a string using python? As you may already know there is a method for string called replace that replaces 1 character with a new given character: '+98 21 445 54 12'.replace('+', '') # output is 98 21 445 54 12 But…
To join lines in
#pycharm #tricks #join #join_lines
PyCharm
first select you lines, then use CTRL+Shift+j
(⌃⇧J) to put them in one line.#pycharm #tricks #join #join_lines
What does
In the above code 2 queries are issued in DB side. First it gets Entry record and then blog is fetched from DB when
You can follow foreign keys in a similar way to querying them. If you have the following models:
Then a call to
#python #django #select_related #join #database #models
select_related
do in Django
?select_related
does a join in case needed on the DB side and reduce query counts. Let's look at an example:# Hits the database.
e = Entry.objects.get(id=5)
# Hits the database again to get the related Blog object.
b = e.blog
In the above code 2 queries are issued in DB side. First it gets Entry record and then blog is fetched from DB when
e.blog
is called. And here’s select_related lookup:# Hits the database.
e = Entry.objects.select_related('blog').get(id=5)
# Doesn't hit the database, because e.blog has been prepopulated
# in the previous query.
b = e.blog
You can follow foreign keys in a similar way to querying them. If you have the following models:
from django.db import models
class City(models.Model):
# ...
pass
class Person(models.Model):
# ...
hometown = models.ForeignKey(
City,
on_delete=models.SET_NULL,
blank=True,
null=True,
)
class Book(models.Model):
# ...
author = models.ForeignKey(Person, on_delete=models.CASCADE)
Then a call to
Book.objects.select_related('author__hometown').get(id=4)
will cache the related Person and the related City:# Hits the database with joins to the author and hometown tables.
b = Book.objects.select_related('author__hometown').get(id=4)
p = b.author # Doesn't hit the database.
c = p.hometown # Doesn't hit the database.
# Without select_related()...
b = Book.objects.get(id=4) # Hits the database.
p = b.author # Hits the database.
c = p.hometown # Hits the database.
#python #django #select_related #join #database #models