Created
December 3, 2013 22:26
-
-
Save gavinwahl/7778717 to your computer and use it in GitHub Desktop.
Abstract (PEP 3119) Django models.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from abc import ABCMeta, abstractmethod | |
class AbstractModelMeta(ABCMeta, type(models.Model)): | |
pass | |
class ABCModel(models.Model): | |
__metaclass__ = AbstractModelMeta | |
class Meta: | |
abstract = True |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo(ABCModel): | |
class Meta: | |
abstract = True | |
@abstractmethod | |
def foo(self): | |
return 1 | |
class Bar(Foo): | |
def foo(self): | |
return 2 | |
# >>> Foo() | |
# Traceback (most recent call last): | |
# File "<console>", line 1, in <module> | |
# TypeError: Can't instantiate abstract class Foo with abstract methods foo | |
# >>> Bar() | |
# <Bar: Bar object> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello Thanks for your post.
I am not a specialist of metaclasses but I have to define abstract Django Models as AbstractModelMeta. And I also need to modifiy some fields for each model subclasses.
I tried to use init_subclass but there is a bug in django which make this solution unusable https://code.djangoproject.com/ticket/34555 .
SO I guess the solution is to redefine new but I have been turning into circles for several days and did not find any solution.
If I overwrite new in ABCModel then I get builtins.TypeError: object.new() takes exactly one argument (the type to instantiate).
When I check the mro of the ABCModel the base.Model is second in the list.
Any help would me most welcome!....
Here is a test