我现在正在思考这个问题一段时间
我正在创建一个聊天应用程序,在 chat.models 中指定了 Room 类,但是,Room 可以与我的项目中的任何内容相关,因为它在外键中使用通用关系。
有没有办法只知道模型名称就知道 Room 与哪个模型相关?
Like:
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 来获取特定字符串的特定模型。有没有办法仅通过“名称”找到模型?
Thanks
http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/#methods-on-contenttype-instances 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)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)