Skip to content

Instantly share code, notes, and snippets.

View valerybriz's full-sized avatar
🐍
Writing poetry in Python

Valery Briz valerybriz

🐍
Writing poetry in Python
View GitHub Profile
@valerybriz
valerybriz / django_example_schema.py
Last active May 2, 2019 21:45
Django example schema
class User(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.TextField()
email = models.TextField()
age = models.PositiveSmallIntegerField()
team = models.ForeignKey(Team, on_delete=models.PROTECT, related_name='users', null=True)
class Team(models.Model):
location = models.TextField()
@valerybriz
valerybriz / user_query.py
Last active May 2, 2019 21:49
example query
user_query = User.objects.filter(name="Ana") # Filter the users by the name "Ana"
user_query = user_query.filter(age__lte=50) # Then get only the users where the age is less than 50
user_query = user_query.exclude(email__isnull=True) # And exclude the users that doesn't have an email
print(user_query)
@valerybriz
valerybriz / hit_queries.py
Last active May 2, 2019 21:51
queries that hit the database
# Iteration
for user in User.objects.all():
print(user.name)
# Slicing
User.objects.all()[:10]
# Pickling or Caching
pickle_str = pickle.dumps(user_queryset)
user_queryset = pickle.loads(pickle_str)
@valerybriz
valerybriz / cached.py
Created April 7, 2019 00:38
cached and not cached queries
# Create the query filtering users with email [email protected]
users = User.objects.get(email="[email protected]")
users.name # Hit the database and retrive the name value
users.name # cached version, no database access
# Create the query filtering teams named tigers
team = Team.objects.get(name="tigers")
team.users.all() # query performed
team.users.all() # query performed again
@valerybriz
valerybriz / create.py
Created May 2, 2019 21:52
Create the query filtering users
# Create the query filtering users with email [email protected]
users = User.objects.get(email="[email protected]")
users.name # Hit the database and retrieve the name value
users.name # cached version, no database access
@valerybriz
valerybriz / create_2.py
Created May 2, 2019 21:53
Create the query filtering teams named tigers
# Create the query filtering teams named tigers
team = Team.objects.get(name="tigers")
team.users.all() # query performed
team.users.all() # query performed again
for user in User.objects.exclude(email__isnull=True).iterator():
print(user.name)
user_queryset = User.objects.all()
# The first hit to the database confirms if at least one object exists.
if user_queryset.exists():
# Another database hit to start fetching the rows in batches.
for user in user_queryset.iterator():
print(user.name)
Team.objects.all().prefetch_related('users')
# Hits the database
team_queryset = Team.objects.get(name="tigers")
# Hits the database again to get the related User objects
user = team_queryset.user