You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django中获取所有通过GenericRelation关联指定模型的模型类?

获取所有关联Comment的Django模型类列表

你的场景是:有一个带GenericForeignKey的Comment模型,其他模型(比如Invoice、Contract)通过GenericRelation与它关联,需要获取所有这类关联模型的类列表,且要求即使没有任何关联实例也能生效(所以不能用Comment.objects.values('content_type'),因为该方法依赖已有数据)。

可以通过遍历Django已注册的所有模型,检查模型是否包含指向Comment的GenericRelation字段来实现,具体代码如下:

from django.apps import apps
from django.contrib.contenttypes.fields import GenericRelation
from yourapp.models import Comment  # 替换成你的Comment模型所在的app路径

def get_models_with_comment_relation():
    related_models = []
    # 遍历所有已注册的模型
    for model in apps.get_models():
        # 检查模型的每个字段
        for field in model._meta.get_fields():
            # 判断字段是否是GenericRelation且关联到Comment
            if isinstance(field, GenericRelation) and field.remote_field.model == Comment:
                related_models.append(model)
                break  # 找到一个就不用继续检查该模型的其他字段了
    return related_models

# 使用示例
related_models = get_models_with_comment_relation()
# 输出结果类似 [Contract, Invoice]

代码说明

  • apps.get_models()会返回Django项目中所有已注册的模型类,不管有没有实例数据。
  • 通过检查模型的字段类型是否为GenericRelation,并且该字段关联的目标模型是Comment,来筛选符合条件的模型。
  • 找到符合条件的字段后就跳出当前模型的字段循环,避免重复添加同一个模型。

内容的提问来源于stack exchange,提问作者Kylelem62

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 22:32:07