首先我们定义两个模型,使用外键关联
from tortoise import fields
from tortoise.models import Model
class Tournament(Model):
"""
This references a Tournament
"""
id = fields.IntField(pk=True)
name = fields.CharField(max_length=100)
#: The date-time the Tournament record was created at
created_at = fields.DatetimeField(auto_now_add=True)
class Event(Model):
"""
This references an Event in a Tournament
"""
id = fields.IntField(pk=True)
name = fields.CharField(max_length=100)
created_at = fields.DatetimeField(auto_now_add=True)
tournament = fields.ForeignKeyField(
"models.Tournament", related_name="events", description="The Tournement this happens in"
)
使用pydantic_model_creator方法直接生成序列化模型,免去了手动编写序列化模型的麻烦,打印schema
from tortoise.contrib.pydantic import pydantic_model_creator
Tournament_Pydantic = pydantic_model_creator(Tournament)
>>> print(Tournament_Pydantic.schema())
{
'title': 'Tournament',
'description': 'This references a Tournament',
'type': 'object',
'properties': {
'id': {
'title': 'Id',
'type': 'integer'
},
'name': {
'title': 'Name',
'type': 'string'
},
'created_at': {
'title': 'Created At',
'description': 'The date-time the Tournament record was created at',
'type': 'string',
'format': 'date-time'
}
}
}
发现根本没有生成外键字段
然后我们使用Tortoise.init_models对模型先进行初始化,其中[]中填写的是模型的位置,后面一个参数是app label, 例如 ‘models’
from tortoise import Tortoise
Tortoise.init_models(["app.models.model"], "models")
# Now lets try again
Event_Pydantic = pydantic_model_creator(Event)
打印schema:
>>> print(Event_Pydantic.schema())
{
'title': 'Event',
'description': 'This references an Event in a Tournament',
'type': 'object',
'properties': {
'id': {
'title': 'Id',
'type': 'integer'
},
'name': {
'title': 'Name',
'type': 'string'
},
'created_at': {
'title': 'Created At',
'type': 'string',
'format': 'date-time'
},
'tournament': {
'title': 'Tournament',
'description': 'The Tournement this happens in',
'allOf': [
{
'$ref': '#/definitions/Tournament'
}
]
}
},
'definitions': {
'Tournament': {
'title': 'Tournament',
'description': 'This references a Tournament',
'type': 'object',
'properties': {
'id': {
'title': 'Id',
'type': 'integer'
},
'name': {
'title': 'Name',
'type': 'string'
},
'created_at': {
'title': 'Created At',
'description': 'The date-time the Tournament record was created at',
'type': 'string',
'format': 'date-time'
}
}
}
}
}
这个序列化模型就带上了外键字段