随笔 - 34  文章 - 0  评论 - 0  阅读 - 5609

内容类型框架-ContentType 模型

 

参考Django官方文档

ContentTypeManager

classContentTypeManager

ContentType 还有一个自定义管理器, ContentTypeManager,它增加了以下方法:

clear_cache()

清除 ContentType 内部的缓存,用来跟踪已经创建了 ContentType 实例的模型。你可能永远都不需要自己调用这个方法,Django 会在需要的时候自动调用它。

get_for_id(id)

通过 ID 查找一个 ContentType。由于该方法与 get_for_model() 使用了相同的共享缓存,所以最好使用该方法,而不是通常的 ContentType.objects.get(pk=id)

get_for_model(model, for_concrete_model=True)

取一个模型类或一个模型的实例,并返回代表该模型的 ContentType 实例。for_concrete_model=False 允许获取代理模型的 ContentType 实例。

get_for_models(*models, for_concrete_models=True)

取一个数量不等的模型类,并返回一个将模型类映射到代表它们的 ContentType 实例的字典。for_concrete_models=False 允许获取代理模型的 ContentType 实例。

get_by_natural_key(app_label, model)

返回由给定的应用程序标签和模型名称唯一标识的 ContentType 实例。本方法的主要目的是允许 ContentType 对象在反序列化过程中通过 自然键 被引用。

当你知道需要使用一个 ContentType,但又不想麻烦地获取模型的元数据来执行手动查找时,这个 get_for_model() 方法特别有用:

>>> from django.contrib.auth.models import User
>>> ContentType.objects.get_for_model(User)
<ContentType: user>
posted on   ldx-wsj  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示