Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get field value in django Model?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading