【问题标题】:FastAPI + Tortoise ORM ForeignKeyField queryFastAPI + Tortoise ORM ForeignKeyField 查询
【发布时间】:2022-08-20 01:05:18
【问题描述】:

fastapi + Tortoise ORM中如何使用用户表查询todo表中的字段

模型.py

class User(models.Model):
    username = fields.CharField(max_length=20, null=False, description=\"username \", unique=True)
    password = fields.CharField(max_length=128, null=False, description=\"password \")
    nickname = fields.CharField(max_length=20, null=True, description=\"nickname \", default=\"hello\")


class Todo(models.Model):

    todoname = fields.CharField(max_length=50, null=False)
    user = fields.ForeignKeyField(\'models.User\', related_name=\'usertodos\', on_delete=fields.CASCADE)

视图.py

@user.get(\"/user/todos\", summary=\"query todos\", response_model=Union[Response200, Response400])
async def usertodos_query():
    data = {
        \"total\": await User.all().count(),
        \"user_todos\": await User.all(),

    }
    return Response200(data=data)

如何在 todos 表中显示 todoname 字段或其他格式可以显示与每个用户关联的 todo 表中的 todoname 字段:

{
  \"code\": 200,
  \"data\": {
    \"total\": 2,
    \"user\": [
      {
        \"id\": 1,
        \"name\": \"user1\",
        \"nickname: : \"user1\",
        \"user_id\": 1
        \"user_todos\": [xxx,xxx,xxx]     ## frome Todo table todoname 
      }
       {
        \"id\": 2,
        \"name\": \"user2\",
        \"nickname: : \"user2\",
        \"user_id\": 1
        \"user_todos\": [xxx,xxx,xxx]     ## frome Todo table todoname
      }
    ]
  },
  \"msg\": \"success\"
}

感谢你们

  • 我不知道你的问题是什么。你在某处有错误吗?究竟是什么不工作?
  • 我想实现为每个用户显示关联的 todoname 的 todoname 字段现在只显示每个用户的信息,但不显示 todoname 字段
  • 到目前为止,您尝试过什么?
  • 我尝试await User.filter(id=pk).usertodos: 不工作AttributeError: \'QuerySet\' object has no attribute \'usertodos\'

标签: fastapi tortoise-orm


【解决方案1】:

您正在尝试通过 Queryset 实例访问模型属性。查看tortoise-orm queryset documentation 并尝试以下操作:

await User.filter(id=pk).first().usertodos

【讨论】:

    猜你喜欢
    • 2021-08-30
    • 2022-08-05
    • 1970-01-01
    • 2021-04-19
    • 2021-02-06
    • 2021-04-16
    • 2020-12-01
    • 1970-01-01
    • 2021-10-21
    相关资源
    最近更新 更多