11

I would like my models to have two string representations: one that is displayed in the backend logs for debugging purposes, and a cleaner one that is displayed to end users when the model is represented in the HTML. Right now, I'm just overriding __unicode__(). Is there a way to do this?

0

2 Answers 2

24

You can also try __repr__ and __str__ for your logging/debugging purposes. It is possible (at least it should be this way) that your logger/debugger uses repr( object ) to log your objects.

Sign up to request clarification or add additional context in comments.

1 Comment

Indeed, __repr__ is used for debugging / internal representation, and either __unicode__ or __str__ for general use. This should have more upvotes.
8

Use properties

class SomeThing( models.Model ):
    foo=
    bar= 
    baz=
    def __unicode__( self ):
        return "{0} {1}".format( self.foo, self.bar )
    @property
    def details( self ):
        return repr( dict( foo=self.foo, bar=self.bar, baz=self.baz ) )

Now you can log someObject.details

1 Comment

What about that __repr__ attribute? Can that be used somehow? So __unicode__ is good to display the string in e.g. admin, and the details is good to dump the object to logs?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.