Get_or_create general relationship in debugging Django and python in general

I ran the code to create shared objects from this demo: http://www.djangoproject.com/documentation/models/generic_relations/

All is well:

>>> bacon.tags.create(tag="fatty") <TaggedItem: fatty> >>> tag, newtag = bacon.tags.get_or_create(tag="fatty") >>> tag <TaggedItem: fatty> >>> newtag False 

But then the use case that interests me for my application:

 >>> 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 

I tried a bunch of random things by looking at another code:

 >>> 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. 

or

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

and etc.

I'm sure someone can give me the correct syntax, but the real problem here is that I have no idea what is going on. I have developed in strongly typed languages ​​for more than ten years (build x86, C ++ and C #), but I'm new to Python. It is very difficult for me to keep track of what happens in Python when such things happen.

In the languages ​​I mentioned earlier, it’s quite simple to calculate such things - check the signature of the method and check your parameters. Looking at the Django documentation for half an hour, I was left as lost. Examining the source for get_or_create (self, ** kwargs) did not help with the fact that there is no method signature, and the code looks very general. The next step is to debug the method and try to figure out what is happening, but it seems a bit extreme ...

It seems to me that some fundamental principle of work is missing here ... what is it? How can I solve such problems on my own in the future?

+4
source share
2 answers

ContentType.objects.get_for_model() will provide you with the appropriate ContentType for the model. Pass the returned object as content_type .

And don't worry too much about β€œgetting” when it comes to Django. Django is mostly insane, and it is recommended to experiment and read the documentation and the source hard.

+7
source

I have compiled some Django debugs here. Two of the best Simon Willison post (in particular, pdb can make you feel at home in Python, starting with the C # / VisualStudio background) and the Django debugging toolbar .

+2
source

Source: https://habr.com/ru/post/1306985/


All Articles