Differentiate between __repr__ and __str__ for model objects
|Reported by:||Tom Tobin <korpios@…>||Owned by:||adrian|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
The __repr__ method of model objects is currently used for all string representations. The Python documentation states that __repr__ "is typically used for debugging, so it is important that the representation is information-rich and unambiguous." Furthermore, __repr__, when it cannot be used to directly recreate the original object (such as is the case with Django model objects), should return "a string of the form '<...some useful description...>'".
Model objects should differentiate between the __repr__ and __str__ methods. __repr__ should return a string useful for, e.g., identification at a Python interpreter prompt, while __str__ should return a string used in, e.g., template substitution.
Example, for a Topping object in a Pizza app:
class Topping (meta.Model): self.name = meta.CharField(maxlength=50) def __repr__ (self): return '<Topping %s>' % self.name def __str__ (self): return self.name
As far as I can tell, the Django codebase generally works correctly at this time if one defines both __repr__ and __str__ methods, since the template code uses %s for string interpolation rather than %r. I have not exhaustively checked the Django codebase, however; I do not consider myself familiar enough with it to understand where all the relevant changes would be required, if any. Documentation would need to be updated to reflect this change.