3👍
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.
6👍
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.