给定带有外键的模型:
Toy --(builder)--> Person
具有相关名称:
Person --(toys_built) --> Toy
使用此代码定义:
class Toy(tortoise.models.Model):
id = tortoise.fields.IntField(pk=True)
name = tortoise.fields.CharField(max_length=32)
builder = tortoise.fields.ForeignKeyField("models.Person", related_name='toys_built')
class Person(tortoise.models.Model):
id = tortoise.fields.IntField(pk=True)
name = tortoise.fields.CharField(max_length=32)
解析给定路径时
Person --(toys_built)--> Toy --(builder)--> ???
按预期返回 QuerySet 而不是 Person。
重现
import tortoise
class Toy(tortoise.models.Model):
id = tortoise.fields.IntField(pk=True)
name = tortoise.fields.CharField(max_length=32)
builder = tortoise.fields.ForeignKeyField("models.Person", related_name='toys_built')
class Person(tortoise.models.Model):
id = tortoise.fields.IntField(pk=True)
name = tortoise.fields.CharField(max_length=32)
async def main():
await tortoise.Tortoise.init(db_url='sqlite://:memory:', modules={'models': ["__main__"]})
await tortoise.Tortoise.generate_schemas()
gepetto = await Person.create(name="Gepheto")
pinocchio = await Toy.create(name="Pinocchio", builder=gepetto)
gepetto_toys_built = await gepetto.toys_built.all()
for toy in gepetto_toys_built:
print(toy.name)
print(f"1 EXPECTED PERSON {gepetto}")
print(f"2 EXPECTED PERSON {pinocchio.builder}")
for toy in gepetto_toys_built:
print(3, type(toy), toy.name)
print(f"4 EXPECTED PERSON {toy.builder}")
await tortoise.Tortoise.close_connections()
if __name__ == '__main__':
tortoise.run_async(main())
预期行为
由于返回的对象是类型类玩具,我希望能够解析 toy.builder,就像实例 pinocchio.builder 一样。但由于某种原因,它返回一个查询集。如我们所见,最后一个 printf 返回一个 QuerySet 但我期望的是一个 Person,如下所示的输出
Pinocchio
1 EXPECTED PERSON <Person>
2 EXPECTED PERSON <Person>
3 <class '__main__.Toy'> Pinocchio
4 EXPECTED PERSON <tortoise.queryset.QuerySet object at 0x7fab33055d00>
如何转换QuerySet
预期Person
对象中的?(或类似的东西)