Django - Get ContentType model by model name (Generic Relations)


Question

I'm thinking about this for a while now,

I'm creating a chat application, in chat.models a class Room is specified, however, a Room can be related to anything in my project, since it uses a generic relation in it's foreign key.

Is there a way to know which model that Room is related knowing only the models name?

Like:

ctype = 'user'

related_to_user = Room.objects.filter(content_type=ctype)

The problem I'm having is, the code below is in a view:

doc = get_object_or_404(Document, id=id)
# get *or create* a chat room attached to this document
room = Room.objects.get_or_create(doc)

If I don't want to use Document model, if I want a model associated to a string, a string that can be anything, without having to write tons of if's to get a specific Model for the specific string. Is there a way to find a model just by it's 'name'?

Thanks

1
18
12/4/2014 7:14:04 PM

Accepted Answer

http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#methods-on-contenttype-instances

user_type = ContentType.objects.get(app_label="auth", model="user")
user_type = ContentType.objects.get(model="user")
# but this can throw an error if you have 2 models with the same name.

Very similar to django's get_model

from django.db.models import get_model
user_model = get_model('auth', 'user')

To use your example exactly:

ctype = ContentType.objects.get(model='user')
related_to_user = Room.objects.filter(content_type=ctype)
41
2/25/2011 5:13:09 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon