watermelon123
watermelon123

Reputation: 417

When to use __str___ method inside Django model?

I have created a Django model with the following attributes.

class Info(models.Model):
    number = models.IntegerField()
    ID = models.IntegerField()
    reading = models.IntegerField()
    date = models.DateField()

I would like to make it so that when a user searches for an 'ID' or 'number' from the database, they are shown the date and reading. Here is my search results code in views.py:

class SearchResultsView(ListView):
    model = Info
    template_name = 'search_results.html'

    def get_queryset(self): 
        query = self.request.GET.get('q')
        reading_list = Info.objects.filter(
            Q(ID__icontains=query) | Q(number__icontains=query)
        )
        return reading_list

And here is my search_results.html template:

<h1>Search Results</h1>

<ul>
  {% for reading in reading_list %}
    <li>
      {{ reading.reading }}, {{ reading.date }}
    </li>
  {% endfor %}
</ul>

I am a little confused as to whether I should include a 'str' method in my model. Will the app be able to print the date and reading using just this code?

Upvotes: 1

Views: 539

Answers (2)

Jun Zhou
Jun Zhou

Reputation: 1117

Based on your current settings, there is no need to add a __str__ function in your model because you are using instance's fields rather than instance itself.

However, if there are any references to the instance itself, e.g. a foreign key to this model or you just want to check the instance itself, adding a __str__ function will increase the readability. You can check the __str__ documentation for details.

Without __str__ field, if you have an Info instance, you will have: <Info: Info object (1)>. After adding a __str___ function and return str(id) for example, you will see <Info: 1>.

It would be great to have a CharField(e.g. description = models.CharField()) in your Info model if you want to add the __str__ function. Then the representation of this object would be <Info: Good Reading>

Upvotes: 2

Saiful Islam
Saiful Islam

Reputation: 34

Whenever an instance of model is created in Django, it displays the object as ModelName Object(1).to make changes to your Django model using this

def __str__(self): 
    return str(self.id) #if its integer, make it str
    return self.name #if its already str. you dont make it str

it changes the display name from ModelName Object(1) to field name of def __str__(self): in your admin panel. and one thing def __str__(self) for python 3 and def __unicode__(self): for python 2

Upvotes: 0

Related Questions