How to create a filter of any related object (ForeignKey field) in Add or Edit page in Admin Site

Hi

I want to know How to create a filter of the related object (ForeignKey field) in Adding or Editing page in Admin Site.

Please guide some code or reference links about this question for me to read more.

General speaking, It is how to customize in add/edit page on the admin site.

My requirement is that I don’t want to list all company, it has to just filter company.is_customer =True for dropdown list in Edit/Add Brand page

model.py

class Company(models.Model):
    company_name = models.CharField('Company Name', max_length=255,unique=True )
    company_address=models.CharField('Company Address',max_length=255 ,null=True, blank=True)
    company_telephone = models.CharField('Company Telephone', max_length=255, null=True, blank=True)
    manager = models.ManyToManyField(Manager)

    is_customer =models.BooleanField('Is Customer',default=True)
    is_subcontractor = models.BooleanField('Is Sub Contractor', default=True)

class DataCenter(models.Model):
    datacenter_name = models.CharField('DataCenter Name', max_length=255)

    company=models.ForeignKey('Company',on_delete=models.CASCADE)
    

I’d start with taking a look at the ModelAdmin.formfield_for_foreignkey method to see whether that will work for you.

Ken

1 Like

Thank you, I can already do it.