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):
retur开发者_开发知识库n [(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?
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.
You don't need anything at all. self
already refers to the relevant class.
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
精彩评论