Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 249
Uriel Bertoche Avatar asked Feb 25 '11 16:02

Uriel Bertoche


1 Answers

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) 
like image 56
Yuji 'Tomita' Tomita Avatar answered Oct 05 '22 20:10

Yuji 'Tomita' Tomita