如何让应用程序的Django模型来自? [英] How to get the app a Django model is from?

查看:143
本文介绍了如何让应用程序的Django模型来自?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有通用关系的模型:

I have a model with a generic relation:

TrackedItem --- genericrelation ---> any model

我希望能够从初始模型中获得跟踪的项目。

I would like to be able to generically get, from the initial model, the tracked item.

我应该可以在任何型号上进行修改,而无需修改。

I should be able to do it on any model without modifying it.

为了做到这一点,我需要获取内容类型和对象标识。获取对象ID很容易,因为我有模型实例,但获取内容类型不是:ContentType.object.filter需要模型(这只是 content_object .__类__.__名称__ )和app_label。

To do that I need to get the content type and the object id. Getting the object id is easy since I have the model instance, but getting the content type is not: ContentType.object.filter requires the model (which is just content_object.__class__.__name__) and the app_label.

我不知道如何以可靠的方式获取模型中的应用程序。

I have no idea of how to get in a reliable way the app in which a model is.

现在我做了$ code> app = content_object .__ module __。split(。)[0] ,但它不适用于django contrib应用程序。

For now I do app = content_object.__module__.split(".")[0], but it doesn't work with django contrib apps.

推荐答案

你不需要得到应用程序或模型来获取内容类型 - 有一个方便的方法来做:

You don't need to get the app or model just to get the contenttype - there's a handy method to do just that:

ContentType.objects.get_for_model(myobject)

尽管名称,它适用于模型类和实例。

Despite the name, it works for both model classes and instances.

这篇关于如何让应用程序的Django模型来自?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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