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

时间:2017-03-29 12:22:55

标签: django django-models

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

现在我有一个名为Shipment

的模型

field = 'order__product__category__description'

此处description是表/模型Category的列名。问题就在这里,只需拥有此模型Shipment和此字段字符串order__product__category__description,如何找到这些模型OrderProductCategory

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

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

3 个答案:

答案 0 :(得分:3)

如果要从模型类(而不是模型实例中的相关实例)获取相关模型,可以使用 Page1 (Refund page) 结合_meta.get_field()来获取相关的模型类:< / p>

field.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 做你想要的。

答案 1 :(得分:1)

我不太了解。无论如何希望你想要这个。

h0 = sigmoid(x0*Wxh + hbias)
h1 = sigmoid(x1*Wxh + Whh*h0 + hbias)
y1 = h1*Why

field = 'order__product__category__description' 实例

获取product
Shipment

然后

product_var = ".".join(field.split("__")[:2]) 

此外,您可以将所有相关信息作为from operator import attrgetter attrgetter(product_var)(shipment_instance)

tuple

希望这有帮助。

答案 2 :(得分:0)

假设您已将字符串拆分为列表,正如您所说:

models = ['order', 'product', 'category']

首先获取每个模型引用的app标签(字符串):

from django.contrib.contenttypes.models import ContentType

app_labels = []

for model in models:
    app_labels.append(ContentType.objects.filter(model=model).values('app_label').first().get('app_label'))

现在您拥有model个名称和app个名称。所以:

from django.apps import apps

model_classes = []

for app, model in zip(app_labels, models):
    model_classes.append(apps.get_model(app, model))

最后,使用您已经知道的_meta属性获取每个模型字段:

for model in model_classes:
    print(model._meta.get_fields())