PyNotes
260 subscribers
125 photos
7 videos
1 file
60 links
**Code is communication**
admin: @Xojarbu
https://t.me/solutions_py for problem solutions
Download Telegram
#Django_ORM #filters
UNION
q1.union(q2)
#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
👍1
#Django_ORM #filters
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
#Django_ORM #filters

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)`
#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.
#Django_ORM #ordering
User.objects.all().order_by('date_joined', '-last_login')
#Django_ORM #ordering
Order queryset by case insensitive manner
User.objects.all().order_by(Lower('username'))
#Django_ORM #Database
Convert existing databases to Django models
python manage.py inspectdb
or
python manage.py inspectdb > models.py
#Django_ORM #Database
Renaming Database table name in model class
#Django_ORM #Database
Rename column name in Database Table:
` a = models.CharField(max_length=40,db_column='column1')`
Note!!!
Use comments liberally not just for yourself, but for anyone else who might have to maintain or enhance your code in the future!!
SearchVector
For searching several fields by annotating to one field

>> from django.contrib.postgres.search import SearchVector
>>> Entry.objects.annotate(
... search=SearchVector('body_text', 'blog__tagline'),
... ).filter(search='Cheese')
[<Entry: Cheese on Toast recipes>, <Entry: Pizza Recipes>]
!! Bare exception is not recommended
Multiple exceptions sample
The finally Statement

output
:
A KeyError occurred!
The finally statement has executed!
Try/Except/Esle/Finally

Output:
`No error occurred
"The finally statement ran!`
r'
Treats the string as a raw string