本文介绍了如何获取 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.获取对象 id 很容易,因为我有模型实例,但获取内容类型不是:ContentType.object.filter 需要模型(它只是 content_object.__class__.__name__)和 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.

现在我做 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:

from django.contrib.contenttypes.models import ContentType

ContentType.objects.get_for_model(myobject)

尽管名称如此,但它适用于模型类和实例.

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

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

08-03 19:21
查看更多