Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: String representation of models

Tags:

python

django

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?

like image 854
Nick Heiner Avatar asked Feb 03 '11 21:02

Nick Heiner


People also ask

What is the use of __ str __ In Django model?

The __str__() method is called whenever you call str() on an object. Django uses str(obj) in a number of places. Most notably, to display an object in the Django admin site and as the value inserted into a template when it displays an object.

What is def __ str __( self in Django?

def __str__( self ): return "something" This will display the objects as something always in the admin interface. Most of the time we name the display name which one could understand using self object.

What is AutoField in Django?

According to documentation, An AutoField is an IntegerField that automatically increments according to available IDs. One usually won't need to use this directly because a primary key field will automatically be added to your model if you don't specify otherwise.

What is Max_length in Django?

The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django's validation using MaxLengthValidator . If you are writing an application that must be portable to multiple database backends, you should be aware that there are restrictions on max_length for some backends.


1 Answers

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.

like image 69
Ski Avatar answered Oct 22 '22 15:10

Ski