Frankline
Frankline

Reputation: 41025

How to override third party libraries in django

I am using a third party Django application i.e. django-geo. One of it's models i.e. LocationType, does not have the __unicode__ method and I would want to add this. See below the current third party model declaration:

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, )

As you can see, the above class does not have a __unicode__ method.

And below is the custom code that I want to add to my application:

LocationType.__unicode__ = lambda location_type: location_type.description

In a normal Django application, where would I add the above monkey-patch code? Is it in any app or I would perhaps have to create another app to house the overriding code?

Upvotes: 1

Views: 2191

Answers (1)

hpelleti
hpelleti

Reputation: 342

Add proxy = True to yout class (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'

Upvotes: 1

Related Questions