Is there a way to call a parent factory's method from a subclass?
The usual super(ThisClass, self)
or ParentClass.method(self)
methods don't work, because self
isn't an instance of the class, it is the object that the factory returns.
class SomethingFactory(factory.DjangoModelFactory):
# Meta, fields, etc
@factory.post_generation
def post(self, create, extracted, **kwargs):
# Some steps
class SomethingElseFactory(SomethingFactory):
@factory.post_generation
def post(self, create, extracted, **kwargs):
super(SomethingElseFactory, self).post(create, extracted, **kwargs)
The error is TypeError: super(type, obj): obj must be an instance or subtype of type
.
(The shortcut super().post(create, extracted, kwargs)
generates the same error.)
How can I access that parent factory SomethingFactory.post
method from the sub-class?
Depending on what you are trying to do in the base class post()
can you pull it out into a function and call it from both places:
def set_attributes(obj):
obj.attr1 = True
obj.attr2 = 1000
class SomethingFactory(factory.DjangoModelFactory):
# Meta, fields, etc
@factory.post_generation
def post(self, create, extracted, **kwargs):
set_attributes(self)
class SomethingElseFactory(SomethingFactory):
@factory.post_generation
def post(self, create, extracted, **kwargs):
set_attributes(self)
# Do some other stuff