首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >模型管理器;TypeError: isinstance() arg 2必须是类型或类型的元组

模型管理器;TypeError: isinstance() arg 2必须是类型或类型的元组
EN

Stack Overflow用户
提问于 2022-02-13 08:24:05
回答 1查看 262关注 0票数 0

我正在尝试测试自定义模型管理器by_week()中的一个方法。在调试它时,我遇到了一个问题,即尝试使用profile.questions.all()self.model.objects.all()查询方法中的所有对象,其中self.model是Question模型。然而,两者都会引发以下错误:*** TypeError: isinstance() arg 2 must be a type or tuple of types。为什么会引发此错误?

作为背景信息:我通过通过管理界面创建实例来创建测试数据,并将数据库中的所有内容转储到一个JSON文件中。

models.py

代码语言:javascript
运行
复制
class QuestionSearchManager(Manager):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def by_week(self, profile):
        # today = datetime.date.today()
        # weekago = today - datetime.timedelta(days=7)
        questions = self.model.objects.all()
        user_tags = profile.questions.all()
        x = self.model.objects.filter(
            tags__name__in=user_tags
        )
        return x


class Post(Model):

    body = TextField()
    date = DateField(default=datetime.date.today)
    comment = ForeignKey('Comment', on_delete=CASCADE, null=True)
    profile = ForeignKey(
        'authors.Profile', on_delete=SET_NULL, null=True,
        related_name='%(class)ss',
        related_query_name="%(class)s"
    )
    score = GenericRelation(
        'Vote', related_query_name="%(class)s"
    )


    class Meta:
        abstract = True


class Question(Post):

    title = CharField(max_length=75)
    tags = ManyToManyField(
        'Tag', related_name="questions", related_query_name="question"
    )
    objects = Manager()
    postings = QuestionSearchManager()

python manage.py

代码语言:javascript
运行
复制
>>> from authors.models import Profile
>>> p = Profile.objects.get(id=2)
>>> p.questions.all()
<QuerySet [<Question: Question object (13)>]>
>>> from posts.models import Question
>>> Question.objects.all()
<QuerySet [<Question: Question object (9)>, <Question: Question object (10)>, <Question: Question object (11)>, <Question: Question object (12)>, <Question: Question object (13)>, <Question: Question object (14)>]>
EN

回答 1

Stack Overflow用户

发布于 2022-02-13 08:34:49

在上面的示例中,从未使用过questions对象。但顺便提一句,您可能希望使用self.model.objects.all()来查询由管理器管理的模型,然后使用它过滤问题。

有点像

代码语言:javascript
运行
复制
    questions = self.get_queryset()
    user_tags = profile.questions.all()
    x = questions.filter(
        tags__name__in=user_tags
    )

您所看到的错误是令人困惑的,因为正在发生的是调用自定义__getattr__,而定制isinstance又使用带有坏参数的isinstance。给定给tags__name__in=的项的类型必须与tags__name字段的类型匹配。大概是字符串,而不是Question实例。

因此,修复将是修复user_tags的值,以匹配tags__name所期望的类型。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71099026

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档