Logging Django Model Instances

Post by Saul Shanabrook

related issue:

I am trying to figure out the best way to log an instance of Django
model. For
django-dumper I log a model every time it is saved and might invalidate

I assumed I wanted to log the repr of the instance, because it is
supposed to have the more information than the str of an object. The
Python docs say:

This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.

It seems to be common practice to define only the __unicode__ on
Django models. In fact, the docs

This is recommended development practice: define only__unicode__() and let Django take care of the conversion to string objects when required.

And when you call repr on an object that returns unicode data from
__unicode__() it will look something like this

'<Model: \xe2\x80\x99>' This is because Django’s db.models.Model implements __repr__ to always return a non unicode string.

So instead I just decide to log the unicode of the object instead (or
str with python 3), or else you get some weird unicode looking stuff in a non unicode string and then get a unicode decode error later on…

I do not pretend to be any sort of an expert on Unicode in Python 2, so
it is very possible I am confused about this whole thing on some level.
The point was that it can be dangerous to call repr on Django model
instances to log them, if you are logging everything as unicode.