Get all related Django model objects

后端 未结 9 1242
攒了一身酷
攒了一身酷 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条回答
  • Django 1.9
    get_all_related_objects() has been deprecated

    #Example: 
    user = User.objects.get(id=1)
    print(user._meta.get_fields())
    

    Note: RemovedInDjango110Warning: 'get_all_related_objects is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()'

    0 讨论(0)
  • 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]
    
    0 讨论(0)
  • 2020-11-27 10:49

    Unfortunately, user._meta.get_fields() returns only relations accessible from user, however, you may have some related object, which uses related_name='+'. In such case, the relation would not be returned by user._meta.get_fields(). Therefore, if You need generic and robust way to merge objects, I'd suggest to use the Collector mentioned above.

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