反向代码提示:
在使用外键的时候,我们需要获取到反向代码提示(即被绑定的model查询绑定model),这个时候需要使用relation字段来提示,(其实你不加也没啥关系,只是个提示作用,在django里面是编辑器和插件提前内置了相关字段所以不用手写)
示例代码如下:
from tortoise.models import Model from tortoise import fields class Tournament(Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=255) events: fields.ReverseRelation["Event"]#仅用于代码提示,注意events必须和Event里面的外键指定的related_name同名 class Event(Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=255) tournament: fields.ForeignKeyRelation[Tournament] = fields.ForeignKeyField( "models.Tournament", related_name="events" ) participants: fields.ManyToManyRelation["Team"] = fields.ManyToManyField( "models.Team", related_name="events", through="event_team" )#注意多对多,两个model里面都要写,虽然复杂了点,但是有代码提示还是很合算的。。through在django里面是指定多对多表的名字和功能,
需要手动创建,这里可能是示例代码不全吧。。得测试 class Team(Model): id = fields.IntField(pk=True) name = fields.CharField(max_length=255) events: fields.ManyToManyRelation[Event]#反向关系,
class Uusers(Model): id = fields.IntField(pk=True) name = fields.IntField() dept: fields.ReverseRelation["Dept"] class Dept(Model): id = fields.IntField(pk=True) name = fields.IntField() user = fields.ForeignKeyField('models.Uusers', on_delete=fields.CASCADE, related_name='dept', verbose_name='所属部门')
# todo 外键正向查找,使用非id字段 # users = await Dept.filter(user__name=79997).values(*fields) # todo 外键正向查找,使用id字段 users = await Dept.filter(user_id=90001).values() # todo 外键反向查找示例 # users = await Uusers.filter(dept__id=5).values()
标签:tortoise,fields,IntField,orm,Model,True,id,name From: https://www.cnblogs.com/pearlcity/p/16611506.html