Django: list all reverse relations of a model

前端 未结 3 1277
故里飘歌
故里飘歌 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: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.

提交回复
热议问题