Home > Enterprise >  How to get field value in django Model?
How to get field value in django Model?

Time:05-24

I have this code

class Book(models.Model):
    name = models.CharField(max_length=70)
    author = models.CharField(max_length=70)
    rating = models.IntegerField(default=None)
    volume = models.IntegerField(null=True, default=None)
    annotation = models.TextField(default=None)
    year = models.IntegerField()
    

I want to get a value from field right in class. For example, "Harry Potter" for name. I don't find method to do it.

CodePudding user response:

I think, you have to show names, that's why you want to access in class.

You can make use of __str__[python-doc] for displaying names.

Try below code:


class Book(models.Model):
    name = models.CharField(max_length=70)
    author = models.CharField(max_length=70)
    rating = models.IntegerField(default=None)
    volume = models.IntegerField(null=True, default=None)
    annotation = models.TextField(default=None)
    year = models.IntegerField()
    
    def __str__(self):
        return f"{self.name}"

Remember: __str__ requires data of str type.

  • Related