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
# 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 |
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
# 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) |
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
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) |
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
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() |
NewerOlder