Django:列出模型的所有反向关系 [英] Django: list all reverse relations of a model
问题描述
我想要我的django应用程序提供任何模型的字段的列表(这将有助于GUI构建本身)。
I would like my django application to serve a list of any model's fields (this will help the GUI build itself).
想像一下这个类步骤
的所有字段可能位于项目
中,我有我的理由:-))
Imagine the classes (ignore the fact that all field of Steps
could be in Item
, I have my reasons :-) )
class Item(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
class Steps(models.Model):
item = models.OneToOneField('Item', related_name='steps')
design = models.BooleanField(default=False)
prototype = models.BooleanField(default=False)
production = models.BooleanField(default=False)
现在,当我想列出一个模型的字段:
Now, when I want to list a model's fields:
def get_fields(model):
return model._meta.fields + model._meta.many_to_many
但我也想得到相关一对一外键列表到我的模型。在我的情况下, Item.steps
不会在该列表中。
But I would also like to get the list of "related" one-to-one foreign keys to my models. In my case Item.steps
would not be in that list.
我发现 model._meta.get_all_field_names
确实包含所有相关的字段。
I have found that model._meta.get_all_field_names
does include all the related fields.
但是当我调用 Item._meta.get_field_by_name('steps')
时,它返回一个持有 RelatedObject
,它不会立即告诉我这是否是一个单一的关系或一对多(我想列出只有一个对 - 一个关系)。
But when I call Item._meta.get_field_by_name('steps')
it returns a tuple holding a RelatedObject
, which does not tell me instantly whether this is a single relation or a one-to-many (I want to list only reversed one-to-one relations).
此外,我可以使用这一段代码:
Also, I can use this bit of code:
from django.db.models.fields.related import SingleRelatedObjectDescriptor
reversed_f_keys = [attr for attr in Item.__dict__.values() \
if isinstance(attr, SingleRelatedObjectDescriptor)]
但我不太满意。
欢迎任何帮助,想法和提示!
Any help, idea, tips are welcome!
干杯
推荐答案
这是改变了(在1.8我认为)和奥利维尔的答案不再工作了。根据 docs ,新的方法是
This was changed (in 1.8 I think) and Olivier's answer doesn't work anymore. According to the docs, the new way is
[f for f in User._meta.get_fields()
if f.auto_created and not f.concrete]
这包括一对一,一对一和多对多。
This includes one-to-one, many-to-one, and many-to-many.
这篇关于Django:列出模型的所有反向关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!