Django's model Model
class defines a __repr__
method that combines the model class name with the string representation of the instance, so that a typical object will show up in the shell or in debugging tools in the following format:
<MyClass: string description of instance>
What I want is for all of my objects instances to show up with their ids in their __repr__
, e.g.
<MyClass 123: string description of instance>
This is for debugging convenience.
Now, it would be easy enough (in principle) to override my __unicode__
methods (which generate the string description of instances) to include the ids, or for that matter to override my __repr__
methods (or to have all my model classes derive from a base class that does so).
However, I'm working with an existing code base and want to avoid changing all the existing model class definitions for this. The quick-and-dirty way to change things is to edit the source code for __repr__
in Django's Model class. But that creates deployment issues as my project always deploys third-party libraries like Django from pip.
So: how can I get Django to include the id in the repr for all object instances without either changing the Django source code or my project model class definitions?
NOTE: I'm thinking some kind of monkey patch to Model.__repr__
should do the trick, but I'm not sure if that would work and if so where in my Django project to do it.
Monkeypatching Model.__repr__
should work. Something like:
def debug_repr(self):
return "<{} {}: {}>".format(self.__class__.__name__, self.pk, self)
Model.__repr__ = debug_repr
This is based on the implementation in the source code.
Where you do this depends on your debugging setup. If you're working in the console you can just type this in directly. If you want to put it in code but not interfere with other deployments, you should probably create a new settings file for your debugging environment and then trigger the monkeypatch that way.