Last active
March 1, 2024 18:30
-
-
Save YuriFontella/08bcdfa9c8dc2b5d73bdec2640441497 to your computer and use it in GitHub Desktop.
relationship prefetch related 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
import asyncio | |
from tortoise import Tortoise, fields | |
from tortoise.connection import connections | |
from tortoise.models import Model | |
class Author(Model): | |
id = fields.IntField(pk=True) | |
name = fields.CharField(max_length=255) | |
class Book(Model): | |
id = fields.IntField(pk=True) | |
title = fields.CharField(max_length=255) | |
author = fields.ForeignKeyField('models.Author', related_name='books') | |
async def create_data(): | |
author1 = await Author.create(name='Autor 1') | |
author2 = await Author.create(name='Autor 2') | |
await Book.create(title='Livro 1', author=author1) | |
await Book.create(title='Livro 2', author=author1) | |
await Book.create(title='Livro 3', author=author2) | |
async def fetch_data(): | |
authors = await Author.all().prefetch_related('books') | |
print(authors) | |
for author in authors: | |
print(f'Autor: {author.name}') | |
for book in author.books: | |
print(f'Livro: {book.title}') | |
async def init(): | |
await Tortoise.init( | |
db_url='asyncpg://postgres:123456@localhost:5432/library', | |
modules={'models': ['__main__']} | |
) | |
await Tortoise.generate_schemas() | |
await create_data() | |
await fetch_data() | |
await connections.close_all() | |
asyncio.run(init()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment