问题描述
我正在尝试使用 Django GenericForeignKey structure 测试模型的 QuerySet,并想模拟它连接到的多个模型。但是,当我尝试使用其中一个模拟模型来证实 Flag
模型(一个带有 GenericForeignKey 的模型)时,会引发 TypeError:
TypeError: Flag() got an unexpected keyword argument 'content_object'
我尝试了下面的代码,注释掉了 content_object
行,并且有效。但是稍后的部分测试需要该属性,因此忽略它不是一个可行的解决方案。
#models.py
class Flag(TimeStampedModel):
text = models.TextField()
content_type = models.ForeignKey(ContentType,on_delete=models.CASCADE)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
#tests.py
...
def setUp(self):
self.quantity = 10
text = ['foo','bar','baz','qux']
for object_ in [mock.Mock(spec=ModelType1),mock.Mock(spec=ModelType2),mock.Mock(spec=ModelType3)]:
for i in range(self.quantity):
object_.pk = i
f = Flag.objects.create(
text=random.choice(text),content_type=ContentType.objects.get_for_model(object_.__class__),object_id=object_.pk,content_object = object_
)
我尝试将该行移出 create 函数并尝试在之后设置它,但这似乎会触发对象状态的错误。
f.content_type = object_
f.save()
...
File ".../python3.9/site-packages/django/contrib/contenttypes/fields.py",line 164,in get_content_type
return ContentType.objects.db_manager(obj._state.db).get_for_model(
File "...Frameworks/Python.framework/Versions/3.9/lib/python3.9/unittest/mock.py",line 630,in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute '_state'
Django==3.2.5,Python 3.9.5
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)