Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override __new__ metaclass method of a model in Django

Tags:

python

django

I am using Django 1.6 and model inheritance in Django. What I wanna do is, hooking new class extending.

It would be done in Python like,

class Meta(type):
    def __new__(cls, name, bases, newattrs):
        do_what_you_want_before()
        result= super(Meta, cls).__new__(cls, name, bases, newattrs)
        do_what_you_want_after()
        return result

class Foo:
    __metaclass__ = Meta

class SubFoo(Foo):
    pass

When this part of code is initialized, custom __new__ method will be invoked.

How can I do that in Django with model inheritance. When you try to do this with Django Models, an error such that, is given:

TypeError: Error when calling the metaclass bases
    metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases

Thank you.

like image 314
Ahmet DAL Avatar asked Aug 27 '14 12:08

Ahmet DAL


People also ask

How do I override a save in Django?

save() method from its parent class is to be overridden so we use super keyword. slugify is a function that converts any string into a slug. so we are converting the title to form a slug basically.

What is __ str __ In Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.

What is Metaclass in Django?

Model Meta is basically the inner class of your model class. Model Meta is basically used to change the behavior of your model fields like changing order options,verbose_name, and a lot of other options. It's completely optional to add a Meta class to your model.


1 Answers

Instead of inheriting from type, inherit from django.db.models.base.ModelBase (source).

like image 192
Maciej Gol Avatar answered Oct 09 '22 15:10

Maciej Gol