简体   繁体   中英

Django- How to Exclude parent class' fields

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

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.

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