Created
January 19, 2022 07:26
-
-
Save doziestar/f4c71add38cfa491855eb0e3b9a7371e to your computer and use it in GitHub Desktop.
Django Query with Q objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.db.models.query import Q | |
from django.db import models | |
# to query a database table, you can use the Django ORM. | |
# assuming you have a table called "users" with the following fields: | |
class User(models.Model): | |
first_name = models.CharField(max_length=50) | |
last_name = models.CharField(max_length=50) | |
email = models.EmailField(max_length=254) | |
password = models.CharField(max_length=50) | |
created_at = models.DateTimeField(auto_now_add=True) | |
updated_at = models.DateTimeField(auto_now=True) | |
def __str__(self): | |
return self.first_name | |
class Profile(models.Model): | |
user = models.OneToOneField(User, on_delete=models.CASCADE) | |
bio = models.TextField(max_length=500, blank=True) | |
# to query a database table, you can use the Django ORM. | |
# query for email that starts with "a" and last name that starts with "b" | |
user = User.objects.filter(email__istartswith='a', last_name__istartswith='b') | |
# query for email that starts with "a" or last name that starts with "b" | |
user = User.objects.filter(Q(email__istartswith='a') | Q(last_name__istartswith='b')) | |
# in the above example, the query is equivalent to: | |
user = User.objects.filter(email__istartswith='a') | User.objects.filter(last_name__istartswith='b') | |
# but the above query is more efficient than the following: | |
user = User.objects.filter(Q(email__istartswith='a') & Q(last_name__istartswith='b')) | |
# using select_related() get the related object | |
user = User.objects.select_related('profile').filter(email__istartswith='a') | |
# or | |
user = User.objects.filter(email__istartswith='a').select_related('profile') | |
# using prefetch_related() get the related object | |
user = User.objects.prefetch_related('profile').filter(email__istartswith='a') | |
# or | |
user = User.objects.filter(email__istartswith='a').prefetch_related('profile') | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment