Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

python - Django: list all reverse relations of a model

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

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.

I have found that model._meta.get_all_field_names does include all the related fields.

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)]

But I'm not very satisfied with this.

Any help, idea, tips are welcome!

Cheers

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 Item._meta.get_fields()
    if f.auto_created and not f.concrete]

This includes one-to-one, many-to-one, and many-to-many.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...