Django管理变更列表筛选/链接到其他模型

Django管理变更列表筛选/链接到其他模型,django,filter,foreign-keys,admin,changelist,Django,Filter,Foreign Keys,Admin,Changelist,我的模型设置如下: class ParentModel(models.Model): some_col = models.IntegerField() some_other = models.CharField() class ChildModel(models.Model) parent = models.ForeignKey(ParentModel, related_name='children') class ToyModel(models.Model)

我的模型设置如下:

class ParentModel(models.Model):
    some_col = models.IntegerField()
    some_other = models.CharField()

class ChildModel(models.Model)
    parent = models.ForeignKey(ParentModel, related_name='children')

class ToyModel(models.Model)
    child_owner = models.ForeignKey(ChildModel, related_name='toys')
现在,在我的管理面板中,当我打开
ParentModel
的变更列表时,我想在列表中显示一个新字段/列,其中包含一个链接,用于打开
ChildModel
的变更列表,但应用了一个过滤器,仅显示所选父项的子项。现在我用这种方法实现了,但我认为有一种更干净的方法,我只是不知道如何:

class ParentAdmin(admin.ModelAdmin)
    list_display = ('id', 'some_col', 'some_other', 'list_children')
    def list_children(self, obj):
        url = urlresolvers.reverse('admin:appname_childmodel_changelist')
        return '<a href="{0}?parent__id__exact={1}">List children</a>'.format(url, obj.id)
    list_children.allow_tags = True
    list_children.short_description = 'Children'        

admin.site.register(Parent, ParentAdmin)
类ParentAdmin(admin.ModelAdmin)
列表显示=('id','some\u col','some\u other','list\u children')
def列表_子项(自身、obj):
url=urlResolver.reverse('admin:appname\u childmodel\u changelist')
返回“”。格式(url,obj.id)
list_children.allow_tags=True
list_children.short_description='children'
admin.site.register(家长、家长管理员)
所以我的问题是,在没有这种“链接黑客”的情况下,有可能实现同样的效果吗?
另外,是否可以在
ParentModel
changelist中的一个单独的列中指出其子项是否有玩具?

我认为您显示
列表\u children
列的方法是正确的。别担心“链接黑客”,没关系

要显示一列以指示对象的任何子对象是否有玩具,只需在
ParentAdmin
类上定义另一个方法,并像前面一样将其添加到
list\u display

class ParentAdmin(admin.ModelAdmin):
    list_display = ('id', 'some_col', 'some_other', 'list_children', 'children_has_toys')
    ...
    def children_has_toys(self, obj):
        """
        Returns 'yes' if any of the object's children has toys, otherwise 'no'
        """
        return ToyModel.objects.filter(child_owner__parent=obj).exists()
    children_has_toys.boolean = True

设置
boolean=True
意味着Django将像对待布尔字段一样呈现“开”或“关”图标。请注意,这种方法要求每个父项都有一个查询(即O(n))。您必须进行测试,看看您在生产中是否获得了可接受的性能。

谢谢您的回答,它确实帮了我很大的忙。我很惊讶django没有一种更优雅的方式来使用变更列表链接特性。不管怎样,谢谢你的帮助,现在我所有的问题都解决了。