Including fields from a OneToOneField in Django Admin

868 views Asked by At

I am attempting to add the fields from a OneToOneField into my admin view. Here is an example of how my models look.

class Customer(BaseUser):
    name = CharField()
    address = CharField()
    secondary_information = OneToOneField("SecondaryCustomerInfo", on_delete=SET_NULL, null=True)


class SecondaryCustomerInfo(models.Model):
    email = EmailField()

And I tried adding in the fields as an inline like this.

class SecondaryCustomerInfoInline(admin.StackedInline):
    model = SecondaryCustomerInfo


class CustomerAdmin(admin.ModelAdmin):
    inlines = [SecondaryCustomerInfoInline]

But I get the error

<class 'user.admin.SecondaryCustomerInfoInline'>: (admin.E202) 'user.SecondaryCustomerInfo' has no ForeignKey to 'user.Customer'.

I'm used to putting the OneToOneField on the secondary model but my coworker asked that I put it on the main Customer model since we will be accessing that information more often. I think switching things around is what is tripping me up. How would I include the fields from SecondaryCustomerInfo on the admin view for Customer?

1

There are 1 answers

0
Artem On BEST ANSWER

The answer would be to use Django Reverse Admin

From its documentation:

Module that makes django admin handle OneToOneFields in a better way. A common use case for one-to-one relationships is to "embed" a model inside another one. For example, a Person may have multiple foreign keys pointing to an Address entity, one home address, one business address and so on. Django admin displays those relations using select boxes, letting the user choose which address entity to connect to a person. A more natural way to handle the relationship is using inlines. However, since the foreign key is placed on the owning entity, django admins standard inline classes can't be used.

class CustomerAdmin(ReverseModelAdmin):
    inline_type = 'stacked'
    inline_reverse = ['secondary_information']