Skip to content

Instantly share code, notes, and snippets.

@kennethnwc
Created February 9, 2021 07:41
Show Gist options
  • Save kennethnwc/b0da6108eab29c47c44a0cb0522a63f4 to your computer and use it in GitHub Desktop.
Save kennethnwc/b0da6108eab29c47c44a0cb0522a63f4 to your computer and use it in GitHub Desktop.
Fastapi Tortoise orm , pydantic relation
from typing import Optional
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from tortoise import Tortoise, run_async
from tortoise.contrib.fastapi import register_tortoise
from tortoise.query_utils import Q
import pandas as pd
from models import Address_Pydantic, Address, Category_Pydantic, Category
app = FastAPI()
origins = [
"http://localhost:3007",
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
register_tortoise(
app,
db_url='sqlite://test.db',
modules={'models' : ['models']},
generate_schemas=True,
add_exception_handlers=True
)
@app.on_event("shutdown")
def shutdown_event():
print("shuting down")
@app.get("/address")
async def get_address(uuid:int = 1):
return await Address_Pydantic.from_queryset_single(Address.get(uuid=uuid))
# return await Address.get(uuid=uuid)
@app.get("/addresses")
async def get_addresses():
return await Address_Pydantic.from_queryset(
Address.all()
)
@app.get("/categories")
async def get_categories():
return await Category_Pydantic.from_queryset(Category.all())
if __name__ == "__main__":
# run_async(run())
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
from tortoise.models import Model
from tortoise import fields, Tortoise
from tortoise.contrib.pydantic import pydantic_model_creator
from typing import Optional
class Address(Model):
uuid = fields.IntField(pk=True,generated=False)
year = fields.IntField()
geocoding = fields.CharField(255, null=True)
class Category(Model):
category = fields.CharField(255)
address: fields.ForeignKeyRelation["Address"] = fields.ForeignKeyField(
"models.Address", related_name="categories"
)
# This is the key line !!!!!!!!!!!!
Tortoise.init_models(["models"], "models")
Address_Pydantic = pydantic_model_creator(
Address, name="Address")
Category_Pydantic = pydantic_model_creator(Category, name="Category")
@JKearnsl
Copy link

Can you tell me how to initialize models that are in different files? molels/tables/user.py and etc

@kennethnwc
Copy link
Author

Sorry, haven't used Tortoise and FastAPI for like years. My best guess would be
Tortoise.init_models(["models.tables.user", "models.tables.address"], "models")
You can pass a list of string to the init_models.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment