Jean Bauer
Jean Bauer

Reputation: 243

Get ContentType id in Django for generic relation

I'm porting a project from Rails to Django with a legacy database. In Rails I had a polymorphic association that allowed me to add a footnote to any row in the database. I'm trying to implement the same thing in the Django app. I found the documentation on Generic Relations and it looks perfect. Unfortunately, I first need to create new fields in my legacy database to hold the ContentType id for the relevant models. I only used the polymorphic association with 2 tables, so all I need are those two corresponding ids from the Django app, but I can't seem to find the appropriate command for looking up a ContentType id in Django.

Any suggestions are most welcome. I tried searching through previous questions but couldn't seem to find what I am looking for. Thank you very much for you time and help.

Upvotes: 18

Views: 14424

Answers (2)

Colleen
Colleen

Reputation: 25499

from the docs

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)

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

I think there's a way to pass just the model name, too... let me know if that would work better and I'll try to find it; I've used it in the past.

Upvotes: 20

horbor
horbor

Reputation: 660

You can also get 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 ContentType ID by model name.

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

Notes : if the name of your model is upper case, please use lower case to search. For example: model = 'bookmark' rather than 'Bookmark'

Upvotes: 10

Related Questions