我正在使用第三方Django应用程序,即django-geo
。其中一个模型,即LocationType
,没有__unicode__
方法,我想添加它。请参阅下面的当前第三方模型声明:
class LocationType(models.Model):
"""Type of the location (city, village, place, locality, neighbourhood, etc.)
This is not intended to contain anything inside it.
"""
uuid = UUIDField(auto=True, blank=False, version=1, help_text=_('unique id'), default="")
description = models.CharField(unique=True, max_length=100)
objects = LocationTypeManager()
class Meta:
verbose_name_plural = _('Location Types')
verbose_name = _('Location Type')
app_label = 'geo'
def natural_key(self):
return (self.uuid.hex, )
如您所见,上面的类没有__unicode__
方法。
以下是我想要添加到我的应用程序的自定义代码:
LocationType.__unicode__ = lambda location_type: location_type.description
在普通的Django应用程序中,我将在哪里添加上面的猴子补丁代码?是在任何应用程序中,或者我可能需要创建另一个应用程序来容纳重写代码?
答案 0 :(得分:0)
将proxy = True添加到您的班级(https://docs.djangoproject.com/en/dev/topics/db/models/#multi-table-inheritance)
class LocationType(models.Model):
"""Type of the location (city, village, place, locality, neighbourhood, etc.)
This is not intended to contain anything inside it.
"""
uuid = UUIDField(auto=True, blank=False, version=1, help_text=_('unique id'), default="")
description = models.CharField(unique=True, max_length=100)
objects = LocationTypeManager()
class Meta:
verbose_name_plural = _('Location Types')
verbose_name = _('Location Type')
app_label = 'geo'
def natural_key(self):
return (self.uuid.hex, )
class MyLocationType(LocationType):
class Meta:
proxy = True
def __unicode__(self):
return 'whatever'