Comments (4)
ok
- Create a folder structure like this:
├── app
│ ├── models.py
├── db.sqlite3
├── main.py
in models.py
from tortoise import fields
from tortoise.models import Model
class Tournament(Model):
# Defining `id` field is optional, it will be defined automatically
# if you haven't done it yourself
id = fields.IntField(pk=True)
name = fields.CharField(max_length=255)
# Defining ``__str__`` is also optional, but gives you pretty
# represent of model in debugger and interpreter
def __str__(self):
return self.name
class Event(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=255)
# References to other models are defined in format
# "{app_name}.{model_name}" - where {app_name} is defined in tortoise config
tournament = fields.ForeignKeyField("models.Tournament", related_name="events")
participants = fields.ManyToManyField(
"models.Team", related_name="events", through="event_team"
)
def __str__(self):
return self.name
class Team(Model):
id = fields.IntField(pk=True)
name = fields.CharField(max_length=255)
def __str__(self):
return self.name
in main.py
from tortoise import Tortoise, run_async
from app.models import Event, Team, Tournament
async def init():
# Here we create a SQLite DB using file "db.sqlite3"
# also specify the app name of "models"
# which contain models from "app.models"
await Tortoise.init(
db_url="sqlite://db.sqlite3", modules={"models": ["app.models"]}
)
# Generate the schema
await Tortoise.generate_schemas()
async def test_task():
# Create instance by save
tournament = Tournament(name="New Tournament")
await tournament.save()
# Or by .create()
await Event.create(name="Without participants", tournament=tournament)
event = await Event.create(name="Test", tournament=tournament)
participants = []
for i in range(2):
team = await Team.create(name="Team {}".format(i + 1))
participants.append(team)
# M2M Relationship management is quite straightforward
# (look for methods .remove(...) and .clear())
await event.participants.add(*participants)
# You can query related entity just with async for
async for team in event.participants:
pass
# After making related query you can iterate with regular for,
# which can be extremely convenient for using with other packages,
# for example some kind of serializers with nested support
for team in event.participants:
pass
# Or you can make preemptive call to fetch related objects,
# so you can work with related objects immediately
selected_events = await Event.filter(
participants=participants[0].id
).prefetch_related("participants", "tournament")
for event in selected_events:
print(event.tournament.name)
print([t.name for t in event.participants])
# Tortoise ORM supports variable depth of prefetching related entities
# This will fetch all events for team and in those team tournament will be prefetched
await Team.all().prefetch_related("events__tournament")
# You can filter and order by related models too
await Tournament.filter(events__name__in=["Test", "Prod"]).order_by(
"-events__participants__name"
).distinct()
async def main():
await init()
await test_task()
if __name__ == "__main__":
run_async(main())
I agree that the documentation examples can be improved
from tortoise-orm.
This is not related to tortoise orm.
from the python docs:
6.4. Await expression
Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function.
from tortoise-orm.
This is not related to tortoise orm.
from the python docs:
6.4. Await expression
Suspend the execution of coroutine on an awaitable object. Can only be used inside a coroutine function.
I get that the error might be from somewhere else... But I would expect the example code from the tutorial to work and be useful otherwise it's useless.
The code I wrote is directly from the docs at the time of me posting it.
How can I make it work? What did I do wrong?
from tortoise-orm.
Thanks!
from tortoise-orm.
Related Issues (20)
- model relationship bugged HOT 8
- why are there three files for one database? HOT 1
- auto_now not working HOT 2
- Field 'DatetimeField' has error when I use '__year' or '__month'. report this:" 'int' object has no attribute 'utcoffset' " HOT 2
- Tortoise ORM integration with FastAPI lifespan ('NoneType' object is not iterable) HOT 4
- update(balance=Wallet.balance+1) how to do this? HOT 1
- Req: concurrent use of multiple databases HOT 4
- model.update_or_create KeyError HOT 3
- Bug: Pydantic 2.7 broke `pydantic_model_creator` HOT 7
- Occasionally during high-frequency queries, there may be differences between SQL statements and query results, leading to KeyError errors. Additionally, Command Out of Sync errors may also be reported during transactions
- QuerySet.count(): IndexError: list index out of range HOT 3
- ConnectionDoesNotExistError, connection was closed in the middle of operation
- Can not to use relation to table with unsigned pk HOT 2
- Documentation is completely broken - it points to the develop branch but says it's for 0.20.1 HOT 9
- Question - how to configure Tortoise for transparent auto-reconnect? HOT 2
- Doubts about the correctness of the result of the count() method HOT 3
- Add proper error messages and a doc page dedicated for testing HOT 3
- Support symmetrical ManyToMany relationships HOT 2
- Bulk Create without returning objects HOT 3
- OperationalError when attempting to filter by annotated field in m2m relation HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from tortoise-orm.