Uri*_*che 18 python django content-type
我现在正在考虑这个问题,
我正在创建一个聊天应用程序,在chat.models中指定了一个类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来获得特定字符串的特定模型.有没有办法找到一个模型只是它的'名称'?
谢谢
Yuj*_*ita 41
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)
| 归档时间: | 
 | 
| 查看次数: | 24815 次 | 
| 最近记录: |