Last active
August 13, 2021 20:27
-
-
Save jkazimierczak/b4895802df118cbd61a54f87dc42e15a to your computer and use it in GitHub Desktop.
SELECT JOIN - tortoise-orm
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 tortoise import fields, Model | |
class Person(Model): | |
id = fields.IntField(pk=True) | |
name = fields.TextField() | |
def __str__(self): | |
return self.name | |
class Pet(Model): | |
id = fields.CharField(30, pk=True) # Can be an IntField too | |
name = fields.TextField() | |
# related_name is the name af attribute that we will use to accet Pet in the Person model | |
owner = fields.ForeignKeyField('models.Person', related_name='pet') | |
def __str__(self): | |
return self.name |
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 models import Person, Pet | |
async def queries(): | |
# Populating the database | |
person = await Person.create(name='Kuba') | |
pet = await Pet.create(id='pet_id', name='Kora', owner=person) | |
# Executing a select query with a JOIN | |
query = Person.get(name='Kuba') | |
person = await query.select_related('pet') | |
# print(query.sql()) # uncomment to see the query | |
print(f'{person} has a pet named {person.pet}') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment