我的模型中有这样的字段:
name = models.CharField(max_length=20, default='Anonymous')
但是当我在该字段中输入更多字符时,没有错误,我可以输入任意数量的字符。我可以在我看来这样做,在admin /中执行,无论如何都没有错误。 有人建议我在保存条目之前制作.full_clean()但不影响,此字段仍允许输入超过20个字符。与其他领域相同。
我非常,非常,非常抱歉我的英语不好。
UPD: 我的models.py的完整代码:
from django.db import models
from django.core.files.storage import FileSystemStorage
import imgboard.const as c
fs = FileSystemStorage(location='/static/img')
class Board(models.Model):
addr = models.CharField(max_length=5, primary_key=True)
# Short description to be displayed on index page
description = models.CharField(max_length=20, verbose_name="Short description")
# Is namefags allowed in this thread
names_allowed = models.BooleanField(default=False, verbose_name="Custom names is allowed")
default_name = models.CharField(max_length=20, default='Anonymous')
# Description to be displayed in header of board page
verbose_description = models.CharField(max_length=400, default='')
# Allowed extensions of files that can be uploaded to this board
allowed_extensions = models.CharField(max_length=1024, default=c.ALLOWED_EXTENSIONS)
# Number of a thread, that will be pinned to top.
pinned_thread_id = models.IntegerField(default=-1)
# Is threads w/o pic allowed
file_required = models.BooleanField(default=False, verbose_name="File is required")
def __str__(self):
return '/'+self.addr+'/ - '+self.description
class Meta:
ordering = ['addr']
class Thread(models.Model):
board = models.ForeignKey(Board, db_column='addr', on_delete=models.CASCADE)
name = models.CharField(max_length=20, default='Anonymous')
last_msg_date = models.DateTimeField(verbose_name='Time of last message published in this thread',
auto_now_add=True)
pic = models.CharField(max_length=3000, default='')
pub_date = models.DateTimeField(auto_now_add=True)
text = models.CharField(max_length=5000)
sage_counter = models.IntegerField(default=0)
bumps = models.IntegerField(default=1)
def __str__(self):
return self.text
class Meta:
ordering = ['-last_msg_date']
class Message(models.Model):
thread = models.ForeignKey(Thread, on_delete=models.CASCADE)
name = models.CharField(max_length=20, default='Anonymous')
pic = models.CharField(max_length=3000, default='')
text = models.CharField(max_length=5000)
pub_date = models.DateTimeField(auto_now=True)
# OP-post mark displays, that this message was written by thread creator
op_post = models.BooleanField(default=False)
# Sage mark displays, that thread will not be bumped by this message
sage = models.BooleanField(default=False)
def __str__(self):
return self.text
class Meta:
ordering = ['-pub_date']
迁移已经运行了很多次,因为很久以前我写了“max_length”,但是刚才注意到了这个bug。 关于DB模式,我听说sqlite根本不限制VARCHAR,max_length只适用于Django后端。
答案 0 :(得分:0)
并非所有数据库都具有有限的字符串长度等功能。在这种情况下,我使用的不是SQLite。
因此,max_length
仅在使用其他数据库(例如PostgreSQL)的情况下起作用。
如果您需要在Django中限制字段长度,请考虑使用字段的validators
关键字参数来定义验证器,该验证器将检查传递的字符串是否太长并引发ValidationException。
此外,SQLite通常不适用于生产环境,因此,如果仅在开发阶段使用它,则也考虑在测试环境中使用在生产环境中使用的实际数据库。仅仅因为这样的差异:您可能会认为您的项目一切正常,但由于这种情况而在生产环境中出现了错误。