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.
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.
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.
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.
Instead of inheriting from type
, inherit from django.db.models.base.ModelBase
(source).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With