Django- How to Exclude parent class' fields

Question:

I have a requirement where I want to exclude all parent fields, just include fields explicitly defined in child.

For brevity, here’s my django code:

#app2 models.py
class EmployeeExtended(app1.Employee):
    boss = models.ForeignKey(User, null=True, blank=True)

#app1 admin.py
class EmployeeExtendedInline(admin.StackedInline):
    model = app2.EmployeeExtended
    fields = ['boss']

class EmployeeAdmin(admin.ModelAdmin):
    inlines = [EmployeeExtendedInline]

This code is working. If I dont give fields, it will include all parent fields also. But I dont want to explicitly write fields=['boss']. Rather I want something like:

for field in EmployeeExtendedOnly_Not_In_Its_Parent:
    fields.append(field)

Please suggest code for EmployeeExtendedOnly_Not_In_Its_Parent

Asked By: jerrymouse

||

Answers:

You might be able to get away with

fields = [f.name for f in app1.EmployeeExtended._meta._fields() if f not in app1.Employee._meta._fields()]

But, to be honest, this is ugly and I cannot see why you extended Employee. Extending make a OneToOneKey between the two models. It seems what you need is a ForeignKey.

Answered By: Meitham

This is how I excluded all of the base class / model from my derived classes / models when they are shown in the admin user interface in Django. Here is my Base class:

class BaseLTI(models.Model):
    id = models.BigAutoField(primary_key=True)
    ...
    def get_excluded_field_names():
        return [f.name for f in BaseLTI._meta.fields]

Here is one of my derived classes:

class Subject(BaseLTI):
    subject = models.CharField(max_length=42, null=False)
    ...

Then in my admin.py file, I did the following:

from .models import BaseLTI, Subject

class SubjectAdmin(admin.ModelAdmin):
    exclude = BaseLTI.get_excluded_field_names();
admin.site.register(Subject, SubjectAdmin)

This will hide all the fields from the base class in the Django Admin UI. I like this because it feels most flexible. For example in BaseLTI I could tweak the list of fields and let a few show if I wanted. Also, when I register each of the derived classes in admin.py, I could tweak the returned exclude list a bit.

Answered By: drchuck
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.