Gor*_*man 9 django admin foreign-keys filter 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)
child_owner = models.ForeignKey(ChildModel, related_name='toys')
Run Code Online (Sandbox Code Playgroud)
现在,在我的管理面板中,当我打开更改列表时,ParentModel我想在list_display中创建一个新字段/列,其中包含一个链接,用于打开更改列表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)
Run Code Online (Sandbox Code Playgroud)
所以我的问题是,如果没有这种"链接黑客",是否有可能实现同样的目标?还可以在ParentModel变更清单的单独栏中指明其子女是否有玩具?
我认为您显示该list_children列的方法是正确的。不用担心“链接黑客”,没关系。
要显示一列来指示对象的任何子对象是否有玩具,只需在ParentAdmin类上定义另一个方法,然后list_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
Run Code Online (Sandbox Code Playgroud)
设置boolean=True意味着 Django 将像布尔字段一样呈现“开”或“关”图标。请注意,此方法需要每个父级一次查询(即 O(n))。您必须进行测试,看看在生产中是否获得了可接受的性能。
| 归档时间: |
|
| 查看次数: |
2237 次 |
| 最近记录: |