Home > database >  Django Admin: How to use OneToMany Field inside list_display?
Django Admin: How to use OneToMany Field inside list_display?

Time:03-04

When listing the "House" Model inside the django admin panel i want to show all Houses but with the PostalCode inside list_display so i can sort them by postal code. Can i use the existing ForeignKey connection between House and HouseAddress to achieve this?

I found some information on how to list parts of the "Houses" inside the "House Addresses" list view (because it has the foreign key field) but not from the "Houses" list view.

Admin.py

class HouseAdmin(admin.ModelAdmin):
    search_fields = ['Name']
    list_display = ['Name']

class HouseAddressAdmin(admin.ModelAdmin):
    search_fields = ['PostalCode']

    model = HouseAddress
    list_display = ['PostalCode']

Model.py

class House(models.Model):
    Name = models.CharField(max_length=150, null=True, blank=False)




class HouseAddress(models.Model):
    PostalCode = models.CharField(max_length=30, null=True, blank=True)
    AddressInfo = models.ForeignKey(House, null=True, blank=True, on_delete=models.CASCADE, related_name='fa')


CodePudding user response:

You might be able to achieve something close to what you need (or at least useful) with list_filter, using something like:

class HouseAdmin(admin.ModelAdmin):
    search_fields = ['Name']
    list_display = ['Name']
    list_filter = ['fa__PostalCode']

This will give you a sidebar where you can click on a postal code and it will filter the houses in that code. list_filter will also provide a default sort.

CodePudding user response:

I hope, I am getting what you want to do exactly. Below is the image of the end result.

Admin.py

from django.contrib import admin
from .models import House, HouseAddress


@admin.register(House)
class HouseAdmin(admin.ModelAdmin):
    search_fields = ['name']
    list_display = ['name', 'get_postal_code']

    def get_postal_code(self, obj):
        return ", ".join([qs.postalcode for qs in obj.fa.all()])


@admin.register(HouseAddress)
class HouseAddressAdmin(admin.ModelAdmin):
    search_fields = ['postalcode']

    model = HouseAddress
    list_display = ['postalcode']

Result: enter image description here

  • Related