Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the length of a TextField in Django?

Tags:

python

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 reference. How do I get the length of a text field in Django? Help and examples appreciated.

like image 902
Ross Walker Avatar asked Nov 23 '25 10:11

Ross Walker


2 Answers

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.

like image 128
Daniel Roseman Avatar answered Nov 25 '25 23:11

Daniel Roseman


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.

like image 34
istruble Avatar answered Nov 26 '25 00:11

istruble