Get all related Django model objects

后端 未结 9 1393
攒了一身酷
攒了一身酷 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:31

    @digitalPBK was close... here is probably what you are looking for using Django's built-in stuff that is used in Django admin for displaying related objects during deletion

    from django.contrib.admin.utils import NestedObjects
    collector = NestedObjects(using="default") #database name
    collector.collect([objective]) #list of objects. single one won't do
    print(collector.data)
    

    this allows you to create what the Django admin displays - the related objects to be deleted.

提交回复
热议问题