Django-按模型名称获取ContentType模型(泛型关系)

2024-05-13 11:53:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我想了一会儿

我正在创建一个聊天应用程序,在chat.models中指定了一个教室,但是,一个房间可以与我项目中的任何内容相关,因为它在外键中使用了一个泛型关系。

有没有办法只知道模特的名字就知道那个房间和哪个模特有关?

比如:

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)

如果我不想使用文档模型,如果我想要一个与字符串相关联的模型,一个可以是任何东西的字符串,而不必编写大量的If来为特定的字符串获取特定的模型。有没有办法只凭“名字”就能找到模特?

谢谢


Tags: orto字符串模型idgetdocobjects
1条回答
网友
1楼 · 发布于 2024-05-13 11:53:52

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)

相关问题 更多 >