Django - 通过模型名称获取ContentType模型(通用关系)

29 投票
1 回答
41764 浏览
提问于 2025-04-16 12:32

我思考这个问题已经有一段时间了,

我正在创建一个聊天应用程序,在聊天的模型中有一个叫做 Room 的类。不过,这个 Room 可以和我项目中的任何东西有关,因为它在外键中使用了通用关系。

有没有办法仅通过模型的名称来知道这个 Room 关联的是哪个模型呢?

比如说:

ctype = 'user'

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

我遇到的问题是,下面的代码是在一个视图中:

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)

如果我不想使用 Document 模型,而是想要一个与字符串关联的模型,这个字符串可以是任何东西,而不想写很多的 if 语句来获取特定字符串对应的特定模型。有没有办法仅通过模型的“名称”来找到模型呢?

谢谢

1 个回答

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.

这和Django里的get_model非常相似。

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

如果完全按照你的例子来用:

ctype = ContentType.objects.get(model='user')
related_to_user = Room.objects.filter(content_type=ctype)

撰写回答