Django - 通过模型名称(Generic Relations)获取ContentType模型 [英] Django - Get ContentType model by model name (Generic Relations)

查看:393
本文介绍了Django - 通过模型名称(Generic Relations)获取ContentType模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在在想这一段时间,

I'm thinking about this for a while now,

我正在chat.models中创建一个聊天应用程序,一个房间被指定,但是房间可以与我的项目中的任何东西相关,因为它使用外键中的通用关系。

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?

喜欢:

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来获取特定的模型具体字符串。有没有办法通过名字找到一个模型?

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'?

谢谢

推荐答案

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

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


Very similar to django's 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)

这篇关于Django - 通过模型名称(Generic Relations)获取ContentType模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆