【问题标题】:How to override third party libraries in django如何在 Django 中覆盖第三方库
【发布时间】:2014-03-07 12:44:29
【问题描述】:

我正在使用第三方 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 应用程序中,我应该在哪里添加上面的猴子补丁代码?是在任何应用程序中,还是我可能必须创建另一个应用程序来容纳覆盖代码?

【问题讨论】:

    标签: django python-2.7 django-models


    【解决方案1】:

    为你的班级添加 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'
    

    【讨论】:

      猜你喜欢
      • 2014-07-04
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2018-08-15
      • 1970-01-01
      • 1970-01-01
      • 2020-05-29
      相关资源
      最近更新 更多