Django 使用 ORM 的相关字段名称获取 Model 名称

neh*_*iah 1 django django-models

我有一个这样的字符串order__product__category__description,它是我的 Django 模型结构的相关表达式

现在我有一个模型叫做 Shipment

field = 'order__product__category__description'

description是 table/model 的列名Category。问题来了,仅通过拥有此模型Shipment和此字段字符串order__product__category__description,我如何找到这些模型Order, Product, Category.

我的用例是我需要将所有 field_names 存储Category在一个列表中。关于如何连接点的任何想法?只剩下两个细节Shipment和那个字段字符串。

首先想到的是拆分__并提出这样的列表,['order','product','category']_meta根据字段名称迭代模型。任何其他优雅的方式将不胜感激。

knb*_*nbk 5

如果你想从模型类中获取相关的模型(而不是从模型实例中获取相关的实例),你可以使用_meta.get_field()combined withfield.related_model来获取相关的模型类:

from django.core.exceptions import FieldDoesNotExist

model = Shipment
lookup = 'order__product__category__description'

for name in lookup.split('__'):
    try:
        field = model._meta.get_field(name)
    except FieldDoesNotExist:
        # name is probably a lookup or transform such as __contains
        break
    if hasattr(field, 'related_model'):
        # field is a relation
        model = field.related_model
    else:
        # field is not a relation, any name that follows is
        # probably a lookup or transform
        break
Run Code Online (Sandbox Code Playgroud)

然后做model你想做的。