Reputation: 17812
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
Upvotes: 2
Views: 1158
Reputation: 4675
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.
Upvotes: 0
Reputation: 9670
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.
Upvotes: 4