【问题标题】:Django - Get ContentType model by model name (Generic Relations)Django - 按模型名称获取 ContentType 模型(通用关系)
【发布时间】:2011-07-04 10:52:50
【问题描述】:

我正在考虑这个问题,

我正在创建一个聊天应用程序,在 chat.models 中指定了一个类 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 来获取特定字符串的特定模型。有没有办法仅通过“名称”找到模型?

谢谢

【问题讨论】:

    标签: python django content-type


    【解决方案1】:

    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)
    

    【讨论】:

    • 如果只有一个具有该名称的模型,有没有办法找出模型来自哪个应用程序?
    • 当然,contenttype.app_label
    • 我的意思是,没有模型,只是名称字符串,在数据库中查找具有该模型的应用程序。我尝试了你所难过的,但没有多大成功
    • app_string = ContentType.objects.get(model="model_string").app_label?这里的最终目标是什么?你在找什么?
    • 我意识到我做错了,谢谢大家。我正在输入像“房间”这样的模型字符串,但它没有找到任何模型......但是“房间”找到了我正在寻找的东西。谢谢!
    猜你喜欢
    • 2016-09-22
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 2020-04-24
    • 2019-01-14
    相关资源
    最近更新 更多