Get all related Django model objects

后端 未结 9 1396
攒了一身酷
攒了一身酷 2020-11-27 09:46

How can I get a list of all the model objects that have a ForeignKey pointing to an object? (Something like the delete confirmation page in the Django admin before DELETE C

9条回答
  •  心在旅途
    2020-11-27 10:49

    Give this a try.

    class A(models.Model):
        def get_foreign_fields(self):
          return [getattr(self, f.name) for f in self._meta.fields if type(f) == models.fields.related.ForeignKey]
    

提交回复
热议问题