我编写fastapi sqlmodel sqlalchemy项目。我在 PyCharm 中遇到类型错误:
expected type 'Literal["*"] | QueryableAttribute', got 'list[Account] | None' instead
错误是由这段代码引起的:
from sqlalchemy.orm import selectinload
class CRUDCounterPartyCommon(
CRUDBase[CounterParty, CounterpartyCommonCreateUpdateSchema, CounterpartyCommonCreateUpdateSchema]
):
async def get_by_uuid(self, db: AsyncSession, *, _uuid: uuid.UUID) -> Optional[CounterParty]:
counterparty = select(CounterParty).where(CounterParty.id == _uuid).options(selectinload(CounterParty.accounts))
警告是由 selectinload 引起的。我该怎么做才能解决这个问题?
更新
mypy 说:
error: Argument 1 to "selectinload" has incompatible type "list[Account] | None"; expected "Literal['*'] | QueryableAttribute[Any]" [arg-type]
这个谜题还有更多内容,您选择不告诉我们。
... select(CounterParty)... options(selectinload(CounterParty.accounts))
对我来说这似乎完全合理
accounts
将是可选的 list[Account]
类型。
考虑施加非 NULL 约束,
所以它至少必须是空列表。
不清楚
Literal["*"] | QueryableAttribute
在哪里
类型来自,但是
MRO
提到了 CounterpartyCommonCreateUpdateSchema
似乎是一个可能的候选人。
至少对于调试来说,
尝试将其删除,看看是否会改变 mypy
所说的内容。
另外,我无法想象你为什么选择将其列出两次。
第二次出现不会产生任何有用的效果。
实现本次通话目标的方法不止一种:
... .options(selectinload(CounterParty.accounts))
在您定义
relationship()
的地方。
我们可以在那里添加一个 , lazy="selectin"
参数,
达到同样的效果。
那么 mypy
就会不太清楚正在发生的事情
也减少了抱怨的理由。