如何为 django admin 包含 Parentalkey?

How to include Parentalkey for django admin?

我有一个 Clusterable 模型以及父键关系。

可聚类模型是一个“Order”模型,其父关系来自“OrderItem”。 相关名称是“项目”。如何将它包含在 django 管理面板中?

For Order model
class OrderAdmin(admin.ModelAdmin):

    fields = ["items"] # from (OrderItem model) but doesn't appear
    search_fields = ['id', 'user']
    list_display = ('user', 'full_name', 'ordered', 'paid', 'total_to_pay')
    list_filter = ('ordered', 'paid',)

你可以定义自己的方法来对对象做任何你想做的事..然后return它并在某处显示它

class OrderAdmin(admin.ModelAdmin):
        fields = ["items"] # from (OrderItem model) but doesn't appear
        search_fields = ['id', 'user']
        list_display = ('user', 'full_name', 'ordered', 'paid', 'total_to_pay', 'some_name')
        readonly_fields = ('some_name',)
        list_filter = ('ordered', 'paid',)


    
        def some_name(self, obj):
            str = obj.items # do whatever you want...
            return str
        some_name.short_description = _('Some name')

或者如果你想要更好的解决方案..使用内联 https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects

ParentalKey 关系只是一个 ForeignKey 关系,具有一些与 Django 管理无关的额外功能,因此 the InlineModelAdmin mechanism 应该可以正常工作:

class OrderItemInline(admin.TabularInline):
    model = OrderItem
    # add fields and any other relevant admin configuration for OrderItem here

class OrderAdmin(admin.ModelAdmin):
    inlines = [OrderItemInline]
    # add other relevant admin configuration for Order here...
    fields = ['user', 'full_name', 'ordered', 'paid', 'total_to_pay']
    search_fields = ['id', 'user']
    list_display = ('user', 'full_name', 'ordered', 'paid', 'total_to_pay')
    list_filter = ('ordered', 'paid',)