[Django]-Django – Get ContentType model by model name (Generic Relations)

59👍

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)

Leave a comment