Get Django ContentType ID for general relationship

I am moving a project from Rails to Django with an outdated database. In Rails, I had a polymorphic association that allowed me to add a footnote to any row in the database. I am trying to implement the same thing in a Django application. I found documentation on a common relationship and it looks perfect. Unfortunately, first I need to create new fields in my old database to store the ContentType identifier for the respective models. I only used a polymorphic relationship with 2 tables, so all I need is those two matching identifiers from a Django application, but I cannot find a suitable command to find the ContentType identifier in Django.

Any suggestions are welcome. I tried to find the previous questions, but could not find what I was looking for. Thank you so much for your time and help.

+7
source share
2 answers

from https://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#django.contrib.contenttypes.generic.GenericForeignKey

You can do:

>>> b = Bookmark.objects.get(url='https://www.djangoproject.com/') >>> bookmark_type = ContentType.objects.get_for_model(b) >>> TaggedItem.objects.filter(content_type__pk=bookmark_type.id, ... object_id=b.id) 

to just instantiate your model and then do ContentType.objects.get_for_model(<instance>).id

I think there is a way to convey only the model name ... let me know if this works better, and I will try to find it; I have used it in the past.

+11
source

You can also get a ContentType ID without creating an instance, which is more efficient if you don't have and don't need an instance, but just want to get the ContentType ID by model name.

ContentType.objects.get(model='bookmark').id

Notes: if your model name is uppercase, use lowercase to search. For example: model = 'bookmark', not 'Bookmark'

+3
source

All Articles