Is it safe to install __new__ on Django model classes?

This question is different from: Using __new__ in classes derived from Django models does not work

This question asks how __new__ work can be done.

This question asks : What are the pitfalls of using __new__ with Django models?

In particular, I have the following code that exists to set the class of a class in a class that needs to know which class it belongs to (i.e., it needs to indicate whether it will be called in the subclass or not). Will it explode in unexpected ways?

 class Director(models.Model, Specializable, DateFormatter, AdminURL, Supercedable): # my own mixin classes # all other properties etc snipped @staticmethod # necessary with django models def __new__(cls, *args, **kwargs): Specializable.create_subclass_translator(cls, install = 'create_from_officer') return models.Model.__new__(cls, *args, **kwargs) 

For completeness, create_subclass_translator does something like this:

 @classmethod def create_subclass_translator(clazz, Baseclass, install=None): def create_from_other_instance(selfclass, old_instance, properties): if selfclass is Baseclass: raise TypeError("This method cannot be used on the base class") # snipped for concision return selfclass(**properties) new_method = classmethod(create_from_other_instance) if install and not hasattr(Baseclass, install): setattr(Baseclass, install, new_method) return new_method 

For those who are wondering what this does, classmethod create_from_other_instance is a factory that mimics an instance of a subclass of a model that changes from one subclass to another by copying over the properties of the base class and setting the ancestor_link property correctly.

+4
source share
1 answer

Since you are calling the __new__ base class __new__ , I would not expect any surprises there - it should just work - and if everything is done wrong, it will immediately fail to instantiate.

You should not have any subtle errors - just write some unit tests that create an instance of this class. If it ever becomes β€œwrong,” the tests will fail.

+2
source

Source: https://habr.com/ru/post/1397641/


All Articles