Skip to content

Instantly share code, notes, and snippets.

@specialunderwear
Last active July 22, 2019 12:12
Show Gist options
  • Save specialunderwear/9d917ddacf3547b646ba to your computer and use it in GitHub Desktop.
Save specialunderwear/9d917ddacf3547b646ba to your computer and use it in GitHub Desktop.
Override model fields of an abstract model baseclass in django, by removing them from the abstract model.
def AbstractClassWithoutFieldsNamed(cls, *excl):
"""
Removes unwanted fields from abstract base classes.
Usage::
>>> from oscar.apps.address.abstract_models import AbstractBillingAddress
>>> from koe.meta import AbstractClassWithoutFieldsNamed as without
>>> class BillingAddress(without(AbstractBillingAddress, 'phone_number')):
... pass
"""
if cls._meta.abstract:
remove_fields = [f for f in cls._meta.local_fields if f.name in excl]
for f in remove_fields:
cls._meta.local_fields.remove(f)
return cls
else:
raise Exception("Not an abstract model")
@maiksprenger
Copy link

Haha, just found while looking to achieve the same for an Oscar project, until django-oscar/django-oscar#1940 is merged. Thanks! :)

@specialunderwear
Copy link
Author

Glad to hear it's useful to someone.

@xxbinxx
Copy link

xxbinxx commented May 25, 2016

💥 💯% useful. Thanks

@rpkilby
Copy link

rpkilby commented Aug 5, 2016

Fortunately, this is no longer necessary in 1.10 since you can override fields on an abstract model.

https://docs.djangoproject.com/en/1.10/topics/db/models/#field-name-hiding-is-not-permitted

@chuckoy
Copy link

chuckoy commented Oct 24, 2017

👍 thanks so much for this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment