我运行代码从这个演示中创建一般相关的对象:http: //www.djangoproject.com/documentation/models/generic_relations/
最初一切都很好:
>>> bacon.tags.create(tag="fatty")
<TaggedItem: fatty>
>>> tag, newtag = bacon.tags.get_or_create(tag="fatty")
>>> tag
<TaggedItem: fatty>
>>> newtag
False
但是我对我的应用程序感兴趣的用例:
>>> tag, newtag = bacon.tags.get_or_create(tag="wholesome")
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/local/lib/python2.6/dist-packages/django/db/models/manager.py", line 123, in get_or_create
return self.get_query_set().get_or_create(**kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/db/models/query.py", line 343, in get_or_create
raise e
IntegrityError: app_taggeditem.content_type_id may not be NULL
查看其他代码后,我尝试了一堆随机的东西:
>>> tag, newtag = bacon.tags.get_or_create(tag="wholesome", content_type=TaggedItem)
ValueError: Cannot assign "<class 'generics.app.models.TaggedItem'>": "TaggedItem.content_type" must be a "ContentType" instance.
或者:
>>> tag, newtag = bacon.tags.get_or_create(tag="wholesome", content_type=TaggedItem.content_type)
InterfaceError: Error binding parameter 3 - probably unsupported type.
等等
我相信有人可以给我正确的语法,但这里真正的问题是我不知道发生了什么。我使用强类型语言(x86 汇编、C++ 和 C#)开发了十多年,但对 Python 很陌生。当这样的事情发生时,我发现很难理解 Python 中发生的事情。
在我之前提到的语言中,很容易弄清楚这样的事情——检查方法签名并检查你的参数。看了半个小时的 Django 文档,我同样迷失了方向。查看 get_or_create(self, **kwargs) 的源代码也没有帮助,因为没有方法签名并且代码看起来非常通用。下一步是调试该方法并尝试弄清楚发生了什么,但这似乎有点极端......
我似乎在这里遗漏了一些基本的操作原则......它是什么?以后如何自行解决此类问题?