Django: list all reverse relations of a model

前端 未结 3 1265
故里飘歌
故里飘歌 2020-12-15 07:59

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

相关标签:
3条回答
  • 2020-12-15 08:04

    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.

    0 讨论(0)
  • 2020-12-15 08:17

    And what about this :

    oneToOneFieldNames = [
        field_name 
        for field_name in Item._meta.get_all_field_names() 
        if isinstance(
            getattr(
                Item._meta.get_field_by_name(field_name)[0], 
                'field', 
                None
            ), 
            models.OneToOneField
        )
    ]
    

    RelatedObject may have a Field attribute for relations. You just have to check if this is a OneToOne field and you can retrieve only what you want

    0 讨论(0)
  • 2020-12-15 08:23

    I've found out that there are methods of Model._meta that can give me what I want.

    my_model = get_model('app_name','model_name')
    # Reverse foreign key relations
    reverse_fks = my_model._meta.get_all_related_objects()
    # Reverse M2M relations
    reverse_m2ms = my_model._meta.get_all_related_many_to_many_objects()
    

    By parsing the content of the relations, I can guess whether the "direct" field was a OneToOneField or whatever.

    0 讨论(0)
提交回复
热议问题