Skip to content Skip to sidebar Skip to footer

How To Get The Length Of A Textfield In Django?

I know that with a regular string you can do x.len() to get the length of it, but a Django model TextField doesn't seem to want that. I have found and looked at the model field re

Solution 1:

Django model instances don't actually expose the fields as field classes: once loaded from the database, they are simply instances of the relevant data types. Both CharField and TextField are therefore accessed as simple strings. This means that, as with any other Python string, you can call len(x) on them - note, this is a built-in function, not a string method. So len(myinstance.mytextfield) and len(myinstance.mycharfield) will work.

Solution 2:

Try len(obj.your_field). This should give you what you want because the result it going to be a an object of the corresponding data type (both TextField fields and CharField fields will be strings). Here is a quick example based on the docs:

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

 person = Person.objects.get(pk=1)

 len(person.first_name)

Also, there is no 'string'.len() method in python unless you have added it somehow.

Post a Comment for "How To Get The Length Of A Textfield In Django?"