get_or_create一般在Django和python调试中的泛型关系

rab*_*ble 5 python django debugging generic-relationship

我运行代码来创建这个演示中的一般相关对象: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
Run Code Online (Sandbox Code Playgroud)

但后来我对我的应用感兴趣的用例:

>>> 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
Run Code Online (Sandbox Code Playgroud)

在查看其他代码后,我尝试了一堆随机的东西:

>>> 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.
Run Code Online (Sandbox Code Playgroud)

要么:

>>> tag, newtag = bacon.tags.get_or_create(tag="wholesome", content_type=TaggedItem.content_type)
InterfaceError: Error binding parameter 3 - probably unsupported type.
Run Code Online (Sandbox Code Playgroud)

等等

我确定有人可以给我正确的语法,但这里真正的问题是我不知道发生了什么.我用强类型语言开发了十多年(x86汇编,C++和C#),但我是Python新手.当发现这样的事情时,我发现很难跟踪Python中发生的事情.

在我之前提到的语言中,将这样的事情弄清楚是相当简单的 - 检查方法签名并检查您的参数.看着Django文档半小时,我就像丢了一样.查看get_or_create(self,**kwargs)的源代码并没有帮助,因为没有方法签名,代码看起来非常通用.下一步是调试方法并尝试弄清楚发生了什么,但这看起来有点极端......

我似乎在这里错过了一些基本的操作原理......它是什么?如何在将来自行解决这类问题?

Ign*_*ams 9

ContentType.objects.get_for_model()会给你一个适合ContentType的模型.将返回的对象传递为content_type.

当谈到Django时,不要过于担心"得到它".Django开始时大多是疯了,鼓励对文档和源代码进行实验和重读.