【问题标题】:How can I supress this type error from Django create_user?如何从 Django create_user 中抑制这种类型错误?
【发布时间】:2022-01-01 18:35:23
【问题描述】:

我从 pylance 收到以下类型错误:

from django.contrib.auth.models import User, AbstractUser
from django.contrib.auth import get_user_model

get_user_model().objects.create_user(**user_data)
#                        ^- Cannot access member "create_user" for type "BaseManager[Any]"
#                           Member "create_user" is unknown Pylance reportGeneralTypeIssues

# User.objects.create_user(**user_data) # same error
# AbstractUser.objects.create_user(**user_data) # same error

由于某种原因,它认为AbstractUser.objects 具有更广泛的类型BaseManager[Any] 而不是UserManager,即使AbstractUser 定义了objects = UserManager()

代码在测试时可以正常工作。

有谁知道我可以如何抑制或消除这种类型错误?

【问题讨论】:

    标签: python django visual-studio-code pylance


    【解决方案1】:

    试试这个:

    from django.contrib.auth.models import User, AbstractUser
    from django.contrib.auth import get_user_model
    # import of `UserManager`
    
    user_manager: UserManager = get_user_model().objects
    
    user_manager.create_user(**user_data)
    

    【讨论】:

    • 不走运Expression of type "BaseManager[Any]" cannot be assigned to declared type "UserManager[Unknown]" / "BaseManager[Any]" is incompatible with UserManager[Unknown]"
    • 等等,你为什么不能只使用User.objects
    • User.objects.create_user 也报类型错误Member "create_user" is unknown :/
    • 你确定你导入了实际上有create_userUser
    猜你喜欢
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2017-03-02
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多