VladiC4T
VladiC4T

Reputation: 236

How to include Parentalkey for django admin?

I have a Clusterable model along with a parental key relationship.

The clusterable model is an "Order" model with the parental relationship from "OrderItem". The related name is "items". How can I include it in the django admin panel?

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',)

Upvotes: 1

Views: 207

Answers (2)

Linum
Linum

Reputation: 341

You can define own method to do whatever you want to do with a objects.. then return it and display it somewhere

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')

or if you want better soluttion.. use inlines https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#inlinemodeladmin-objects

Upvotes: 0

gasman
gasman

Reputation: 25227

A ParentalKey relation is just a ForeignKey relation with some extra functionality that isn't relevant to the Django admin, so the InlineModelAdmin mechanism should work fine for it:

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',)

Upvotes: 2

Related Questions