[英]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. 我知道使用常规字符串可以执行x.len()来获取其长度,但是Django模型TextField似乎不需要这样做。 I have found and looked at the model field reference .
我找到并查看了模型领域参考 。 How do I get the length of a text field in Django?
如何获取Django中文本字段的长度? Help and examples appreciated.
帮助和示例赞赏。
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. Django模型实例实际上并未将字段公开为字段类:从数据库加载后,它们只是相关数据类型的实例。 Both CharField and TextField are therefore accessed as simple strings.
因此,CharField和TextField都可以作为简单字符串访问。 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. 这意味着,与其他任何Python字符串一样,您可以在它们上调用
len(x)
-注意,这是一个内置函数,而不是字符串方法。 So len(myinstance.mytextfield)
and len(myinstance.mycharfield)
will work. 因此
len(myinstance.mytextfield)
和len(myinstance.mycharfield)
可以工作。
Try len(obj.your_field)
. 尝试
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). 这应该可以为您提供所需的信息,因为结果将是对应数据类型的对象(TextField字段和CharField字段均为字符串)。 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. 另外,除非您以某种方式添加了它,否则python中没有'string'.len()方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.