Skip to content

Instantly share code, notes, and snippets.

@jkazimierczak
Last active August 13, 2021 20:27
Show Gist options
  • Save jkazimierczak/b4895802df118cbd61a54f87dc42e15a to your computer and use it in GitHub Desktop.
Save jkazimierczak/b4895802df118cbd61a54f87dc42e15a to your computer and use it in GitHub Desktop.
SELECT JOIN - tortoise-orm
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
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