简体   繁体   中英

How to not display foreign key as list in Django admin object page?

I have two basics models:

class Address(models.Model):
    ...

class Company(models.Model):
    address = models.ForeignKey(Address, related_name='address')
    billing_address = models.ForeignKey(Address, related_name='billing_address')

I have make a model for address in order to don't repeat the code, because of the two addresses.

From a Django perspective everything seems logic. But in the Django administration it is not logic to have a list since each compagny have its own address. It should be more conform to have something like an inline but limited to one element.

So basically, the only solution I found for the moment is to do:

class Company(models.Model):
    street_address = models.CharField(max_length=200)
    ...
    street_billing_address = models.CharField(max_length=200)
    ...

But, once again the problem with this solution is the duplicated code... :(

Any idea for a solution?

You can use two inlines, each limited to one element. For example:

class AddressInline(admin.StackedInline):
    model = Address
    fk_name = "address"
    max_num = 1

class BillingAddressInline(admin.StackedInline):
    model = Address
    fk_name = "billing_address"
    max_num = 1


class CompanyAdmin(admin.ModelAdmin):
    # ...
    inlines = [AddressInline, BillingAddressInline]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM