Mirage
Mirage

Reputation: 31568

How can I use similar functions across all Models in Django

I have three functions which I need in every Django Model:

def __unicode__(self):
            return self.MODELNAME_name

def get_absolute_url(self):
            return "/MODELNAME/list/" 

def get_fields(self):
            return [(field, field.value_to_string(self)) for field in MODELNAME._meta.fields]

The only thing different is the MODELNAME

How can I use inheritance so that I use three functions in one class and other inherit from it?

Upvotes: 1

Views: 71

Answers (3)

lprsd
lprsd

Reputation: 87155

Daniel's answer is right. But if you want a string, that is the name of the current model, you can use:

self._meta.verbose_name_raw

Upvotes: 0

Gabi Purcaru
Gabi Purcaru

Reputation: 31564

You could use multiple inheritance:

class CommonFunctions(object):
    def __unicode__(self):
        return self.MODELNAME_name
    def get_absolute_url(self):
        return "/MODELNAME/list/" 
    def get_fields(self):
        return [(field, field.value_to_string(self)) for field in MODELNAME._meta.fields]

class ZeModel(models.Model, CommonFunctions):
    [...]

x = ZeModel()
x.get_absolute_url()

(Make sure you replace MODELNAME with self.__class__.__name__)

I did not test this, but it should work.

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599788

You don't need anything at all. self already refers to the relevant class.

Upvotes: 0

Related Questions