[Django]-Object word is assign to models automatically in Django

1👍

In your models.py file add this method at the end

def __str__(self):
    return self.field_name

field_name is the field of your model which you want to display

2👍

This is the default implementation of the __str__ method [python-doc] for a Django model. You can implement your own __str__ method for example:

class Musician(models.Model):
    # …

    def __str__(self):
        return f'Musician {self.pk}'

2👍

Play with def str(). Return what you want to see in admin panel. Read about repr and str. You will get all what is happening here.

def __str__() :
    return "not object" # you can return your variables or methods or expressions here

2👍

The str method in Python represents the class objects as a string – it can be used for classes. The str method should be defined in a way that is easy to read and outputs all the members of the class. This method is also used as a debugging tool when the members of a class need to be checked.

The str method is called when the following functions are invoked on the object and return a string:

    print()
    str()

If we have not defined the str, then it will call the repr method. The repr method returns a string that describes the pointer of the object by default (if the programmer does not define it).

Leave a comment