我正在尝试测试自定义模型管理器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
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
>>> 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)>]>
发布于 2022-02-13 08:34:49
在上面的示例中,从未使用过questions
对象。但顺便提一句,您可能希望使用self.model.objects.all()
来查询由管理器管理的模型,然后使用它过滤问题。
有点像
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
所期望的类型。
https://stackoverflow.com/questions/71099026
复制相似问题