All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.py.rules.python.S6554.html Maven / Gradle / Ivy

There is a newer version: 4.23.0.17664
Show newest version

This rule ensures that Django models have a __str__ method defined.

Why is this an issue?

The __str__ method in Django models is used to represent the model instance as a string. For example, the return value of this method will be inserted in a template when displaying an object in the Django admin site. Without this method, the model instance will be represented by its object identifier, which is not meaningful to end-users. This can result in confusion and make debugging more difficult.

How to fix it

To fix this issue, the Django model must define a __str__ method that returns a string representation of the instance. This string should be meaningful to end-users and provide information about the model instance.

Code examples

Noncompliant code example

from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=100)

Compliant solution

from django.db import models

class MyModel(models.Model):
    name = models.CharField(max_length=100)

    def __str__(self):
        return self.name

Resources

Documentation

https://docs.djangoproject.com/en/4.1/ref/models/instances/#django.db.models.Model.str[Django Model.str()]





© 2015 - 2024 Weber Informatics LLC | Privacy Policy