值太长的类型字符变化(100)----最近切换数据库,在db中没有做任何事情 [英] value too long for type character varying(100)----recently switched database, didn't do anything in db

查看:241
本文介绍了值太长的类型字符变化(100)----最近切换数据库,在db中没有做任何事情的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近切换到postgresql,我以为一切都很好,直到我意识到当我发布,我得到的值太长,类型字符变化(100)。现在我去搜索它,看到一些类似的问题,但是当我尝试了一些解决方案的时候,他们都没有工作。我会解释为什么我的问题在我看来是不同的。我在models.py中有这个代码

  class Post(models.Model):
url = models.URLField max_length = 250,blank = True,null = True)

slug = models.CharField(max_length = 255,unique = True)
objects = models.Manager()

@property

def save(self,* args,** kwargs):
self.slug = uuslug(self.title,instance = self,max_length = 255)
super(Post,self).save(* args,** kwargs)

一些推荐的解决方案,我确实尝试将我的max_length更改为100.我不知道为什么会发生这种情况,我在db中没有任何东西。我最近切换到postgresql。你能帮我解决这个错误发生的原因,以及如何解决这个错误?我应该离开uuslug吗?



完整型号

 
class Category(models.Model):

name = models.CharField(max_length = 128,unique = True)
description = models.TextField(verbose_name =('describe' )
author = models.ForeignKey(settings.AUTH_USER_MODEL)


def __unicode __(self):
return self.name

def get_absolute_url(self):
return/ category /%s /%self.name

def my_handler(sender,instance,created,** kwargs):
action .send(instance.author,verb ='following',target = Category)
post_save.connect(my_handler,sender = Category)


class Post(models.Model) :
category = models.ForeignKey(Category,verbose_name =('community'))
pub_date = models.DateTimeField(auto_now_add = True)
url = models.URLField(max_length = 250,blank = True,null = True)
video = EmbedVideoField(verbose_name ='link',help_text =Youtube,blank = True,null = True)

title = models.CharField(max_leng th = 50)
moderator = models.ForeignKey(User)
views = models.IntegerField(default = 0)
slug = models.CharField(max_length = 255,unique = True)
objects = models.Manager()#default manager
content = RichTextUploadingField(config_name ='default')
rank_score = models.FloatField(default = 1)
image = models.ImageField upload_to ='images',blank = True,null = True)
thumbnail = models.ImageField(upload_to ='images',blank = True,null = True)


@property
def domain(self):
long_url = urlparse(self.url).netloc if self.url else彼此友好
return long_url.split('。 ,1)[1]如果long_url.split('。',1)[0] =='www'else long_url
def save(self,* args,** kwargs):
self。 slug = uuslug(self.title,instance = self,max_length = 255)
super(Post,self).save(* args,** kwargs)
def __unicode __(self):
返回s elf.title

这是完整的追溯



T

  raceback:
文件env / local / lib / python2.7 / site-packages / django / core /handlers/base.pyin get_response
132. response = wrapped_callback(request,* callback_args,** callback_kwargs)
文件env / local / lib / python2.7 / site-packages / django / view / generic / base.pyin view
71. return self.dispatch(request,* args,** kwargs)
文件env / local / lib / python2.7 / site-packages / $ _
34. return bound_func(* args,** kwargs)
文件env / local / lib / python2.7 / site-packages / django / contrib / awrite / decorators.py_wrapped_view
22. return view_func(request,* args,** kwargs)
文件env / local / lib / python2.7 / site-packages / django / utils / decorator.pyin bound_func
30. return func .__ get __(self,type(self))(* args2,** kwargs2)
文件ebagu / main / vie ws.pyin dispatch
191. return super(PostCreateView,self).dispatch(request,* args,** kwargs)
文件env / local / lib / python2.7 / site-packages /django/views/generic/base.py在dispatch
89. return handler(request,* args,** kwargs)
文件env / local / lib / python2.7 / site-packages /django/views/generic/edit.py在post
249. return super(BaseCreateView,self).post(request,* args,** kwargs)
文件env / local / lib / python2.7 / site-packages / django / views / generic / edit.py在post
215. return self.form_valid(form)
文件ebagu / main / views.pyin form_valid
186. self.object.save()
保存
中的文件ebagu / main / models.py66. super(Post,self).save(* args,** kwargs)
保存
734中的文件env / local / lib / python2.7 / site-packages / django / db / models / base.py。force_update = force_update,update_fields = update_fields)
文件env / local / lib / python2.7 / site-packages / django / db / models /base.py在save_base
762. updated = self._save_table(raw,cls,force_insert,force_update,using,update_fields)
文件env / local / lib / python2.7 / site-packages /django/db/models/base.pyin _save_table
846. result = self._do_insert(cls._base_manager,using,fields,update_pk,raw)
文件env / local / lib / python2 _do_insert
中的.7 / site-packages / django / db / models / base.py885. using = using,raw = raw)
文件env / local / lib / python2.7 / site返回getattr(self.get_queryset(),name)(* args,** kwargs)
文件env / local / _insert
920中的lib / python2.7 / site-packages / django / db / models / query.py。return query.get_compiler(using = using).execute_sql(return_id)
文件env /在execute_sql
974中的local / lib / python2.7 / site-packages / django / db / models / sql / compiler.pycursor.execute(sql,params)
文件env / lo执行
79中的cal / lib / python2.7 / site-packages / django / db / backends / utils.pyreturn super(CursorDebugWrapper,self).execute(sql,params)
文件执行
中的env / local / lib / python2.7 / site-packages / django / db / backends / utils.py 64. return self.cursor.execute(sql,params)
文件env _local/lib/python2.7/site-packages/django/db/utils.py__exit__
97. six.reraise(dj_exc_type,dj_exc_value,traceback)
文件env / local / lib /python2.7/site-packages/django/db/backends/utils.py执行
64. return self.cursor.execute(sql,params)

异常类型:DataError在/ add_post /
异常值:值太长,类型字符变化(100)


解决方案

我不认为你需要帮助修复这个问题,就像你需要帮助调试一样。一旦问题清楚,解决方案似乎也很清楚。 Traceback可能有点不清楚,因为它经历了如此多的Django源代码,并没有告诉你哪些领域有问题。



背景到这个问题



首先,我们在保存 Post 实例时遇到问题。那么,看看你在模型定义中的所有这些领域:

  ... 
url = models。 URLField(max_length = 250,blank = True,null = True)
video = EmbedVideoField(verbose_name ='link',help_text =Youtube,blank = True,null = True)
content = RichTextUploadingField config_name ='default')
image = models.ImageField(upload_to ='images',blank = True,null = True)
thumbnail = models.ImageField(upload_to ='images',blank = null = True)

这些可能不会像文本字段,但是它们中的很多都是文本字段的变体,因为如果您想到这一点,您可能不会将整个文件存储在数据库中。你会做什么(和默认情况下Django做的)将文件存储在某个磁盘上的某个位置,然后在数据库中存储路径到该文件,以便您可以在需要时检索它。



此外,将数据库中的文件路径存储为 LongText 或其他任何内容可能是浪费的, code> FileField 我们有意义,我们有一个包含 max_length 的字段,无论我们是否指定。因此,所有上述字段都有一个隐含的 max_length 。你可以通过阅读Django的源代码来找到它。



源代码示例



我从来没有使用过 EmbedVideoField ,但事实证明是 models.URLField 的子类,这意味着它有 max_length 默认情况下设置为200 如果您没有指定一个。



此外,您的各种 ImageField s只是 FileField 的子类, max_length 默认值为100的模型/字段/ files.py#L234rel =nofollow noreferrer>。



如何在未来调试这样的问题?



现在,这个不帮助我们知道您的字段中的哪个在这种情况下发生错误。为此,我可能会在代码中设置一个断点,可能在这里:

 文件ebagu / main / models.py 在save 
66. super(Post,self).save(* args,** kwargs)

通过设置断点,我的意思是:



转到上述模块中的第65行, ebagu / main /models.py 并输入以下内容并保存模块: import pdb; pdb.set_trace()



(我实际上对 ipdb 我自己,但是这需要Ipython,我也很喜欢...)



运行本地服务器,并运行产生此问题的步骤。您将最终提交表单,如果您查看启动服务器的控制台,则最终将在第65行转储到shell中。此shell是 pdb shell ,它具有与普通shell不同的规则,但是您可以评估即将被保存的 Post 实例,通过查看实例本身的各个字段, self ,并在该方法调用的上下文中运行Python代码:

 (pdb)len(self.image.path)

使用它,我将手动评估各个字段,并查看哪个具有这个真正长的条目,阻止保存(可能是您的



具有警告的解决方案



或者,您可以向所有这些添加一个 max_length ,但要预先警告您最有可能需要执行m 数据库迁移,因为您更改的任何有限的文本字段,因为您的数据库仍将根据列的定义来验证输入的长度。 这是一个很好的StackOverflow答案,正好看这个问题



脚注



为什么在切换到Postgresql之前没有出现?有各种潜在的原因,但这可能与前一个数据库的设置方式有关,以及如何设置Postgresql数据库(手动与Django迁移?)。



<这也可能与您是否改变了存储这些东西的方式有关。您是否更改了 MEDIA 设置,以便存储文件的路径长得多?



您真正应该做的是直接查看您的数据库。打开一个 psql 实例,并要求它为你描述你的表。它会告诉您哪些字段限制为100个字符,那些字段会给您带来问题。


I recently switched to postgresql, I thought everything worked fine until I realized when I make post I get value too long for type character varying(100). Now I googled it, and saw some similar questions but when I tried some solutions there none of them worked. I will explain why my question is different in my opinion. I have this code in models.py

class Post(models.Model):
    url = models.URLField(max_length=250, blank=True, null=True)

    slug = models.CharField(max_length=255, unique=True)
    objects = models.Manager()    

@property

def save(self, *args, **kwargs):
    self.slug = uuslug(self.title, instance=self, max_length=255)
    super(Post, self).save(*args, **kwargs)

As I saw some recommended solutions, I did try changing my max_length to 100. I have no idea why this is happening, I don't have anything in db. I recently switched to postgresql. Can you help me why this error is occurring and how I can fix it? should I move away from uuslug?

Full model

.
class Category(models.Model): 

    name = models.CharField(max_length=128, unique=True)
    description = models.TextField(verbose_name=('describe'))
    author = models.ForeignKey(settings.AUTH_USER_MODEL)


    def __unicode__(self): 
        return self.name

    def get_absolute_url(self):
        return "/category/%s/" %self.name

def my_handler(sender, instance, created, **kwargs):
    action.send(instance.author, verb='following', target=Category)
post_save.connect(my_handler, sender=Category)


class Post(models.Model):
    category = models.ForeignKey(Category, verbose_name=('community'))
    pub_date = models.DateTimeField(auto_now_add = True)
    url = models.URLField(max_length=250, blank=True, null=True)
    video = EmbedVideoField(verbose_name='link',help_text="Youtube", blank=True, null=True) 

    title = models.CharField(max_length = 50)
    moderator = models.ForeignKey(User)
    views = models.IntegerField(default=0)
    slug = models.CharField(max_length=255, unique=True)
    objects = models.Manager()            # default manager
    content = RichTextUploadingField(config_name='default')
    rank_score = models.FloatField(default= 1)
    image = models.ImageField(upload_to='images',blank=True, null=True)
    thumbnail = models.ImageField(upload_to='images', blank=True, null=True)


    @property
    def domain(self):
        long_url = urlparse(self.url).netloc if self.url else "be kind to one another"
        return long_url.split('.', 1)[1] if long_url.split('.', 1)[0] == 'www' else long_url
    def save(self, *args, **kwargs):
        self.slug = uuslug(self.title, instance=self, max_length=255)
        super(Post, self).save(*args, **kwargs)
    def __unicode__(self):
        return self.title 

Here's full Traceback

T

raceback:
File "env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/base.py" in view
  71.             return self.dispatch(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/contrib/auth/decorators.py" in _wrapped_view
  22.                 return view_func(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "ebagu/main/views.py" in dispatch
  191.      return super(PostCreateView, self).dispatch(request, *args, **kwargs)       
File "env/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch
  89.         return handler(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  249.         return super(BaseCreateView, self).post(request, *args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/views/generic/edit.py" in post
  215.             return self.form_valid(form)
File "ebagu/main/views.py" in form_valid
  186.          self.object.save()
File "ebagu/main/models.py" in save
  66.       super(Post, self).save(*args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/db/models/base.py" in save
  734.                        force_update=force_update, update_fields=update_fields)
File "env/local/lib/python2.7/site-packages/django/db/models/base.py" in save_base
  762.             updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "env/local/lib/python2.7/site-packages/django/db/models/base.py" in _save_table
  846.             result = self._do_insert(cls._base_manager, using, fields, update_pk, raw)
File "env/local/lib/python2.7/site-packages/django/db/models/base.py" in _do_insert
  885.                                using=using, raw=raw)
File "env/local/lib/python2.7/site-packages/django/db/models/manager.py" in manager_method
  127.                 return getattr(self.get_queryset(), name)(*args, **kwargs)
File "env/local/lib/python2.7/site-packages/django/db/models/query.py" in _insert
  920.         return query.get_compiler(using=using).execute_sql(return_id)
File "env/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py" in execute_sql
  974.                 cursor.execute(sql, params)
File "env/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  79.             return super(CursorDebugWrapper, self).execute(sql, params)
File "env/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)
File "env/local/lib/python2.7/site-packages/django/db/utils.py" in __exit__
  97.                 six.reraise(dj_exc_type, dj_exc_value, traceback)
File "env/local/lib/python2.7/site-packages/django/db/backends/utils.py" in execute
  64.                 return self.cursor.execute(sql, params)

Exception Type: DataError at /add_post/
Exception Value: value too long for type character varying(100)

解决方案

I don't think you need help fixing this problem, so much as you need help debugging it. Once the problem is clear, the solution seems clear as well. The Traceback is perhaps a bit unclear because it's going through so much Django source code and it's not telling you which of your fields is having an issue.

Background To This Issue

To start with, we're having problems saving a Post instance. Well, look at all of these fields you have in your model definition:

 ...
  url = models.URLField(max_length=250, blank=True, null=True)
  video = EmbedVideoField(verbose_name='link',help_text="Youtube", blank=True, null=True) 
  content = RichTextUploadingField(config_name='default')
  image = models.ImageField(upload_to='images',blank=True, null=True)
  thumbnail = models.ImageField(upload_to='images', blank=True, null=True)

These may not look like text fields, but a lot of them are variations on text fields because, if you think about it, you're probably not going to store whole files in your database. What you will do instead (and what Django does by default) is store the file somewhere on some disk and then in the database you would store the path to that file so you can retrieve it when you need to.

Further, it's probably a waste to store file-paths in the db as LongText or whatever, so every FileField we have means we've got a field with a max_length whether we specify it or not. Thus, all of the above fields have an implicit max_length. You can actually find this out by reading the Django source code.

Source Examples

I've never used EmbedVideoField, for example, but it turns out to be a subclass of models.URLField, which means it has a max_length by default set to 200 if you do not specify one.

Moreover, your various ImageFields are just subclasses of FileField, which has a max_length default of 100.

How to Debug Problems Like This In the Future?

Now, this doesn't help us to know which of your fields is throwing an error in this case. For that, I would probably set a breakpoint somewhere in the code, probably here:

File "ebagu/main/models.py" in save
   66.       super(Post, self).save(*args, **kwargs)

By "set a breakpoint", I mean the following:

Go to line 65 in the module mentioned above, ebagu/main/models.py and enter the following and save the module: import pdb; pdb.set_trace()

(I actually have a strong preference for ipdb myself, but that requires Ipython, which I also have a strong preference for...)

Run your local server, and run through the steps that produced this issue. You will end up submitting your form and if you look at the console where you started your server, you'll eventually be dumped into a shell right at line 65. This shell is a pdb shell, which has different rules from a normal shell, but you can evaluate your about-to-be-saved Post instance, by looking at the various fields on the instance itself, self, and running Python code in the context of that method call:

(pdb) len(self.image.path)

Using that, I would manually evaluate the various fields and look at which one has this really long entry that is choking the save (probably one of your ImageFields).

Solution with Warnings

Alternately, you can just add a max_length to all of these, but be forewarned that you will most likely need to perform database migrations for any limited text field you change because your database is still going to verify the length of the input against how the column is defined. Here's a good StackOverflow answer looking at exactly this problem.

Footnote

Why didn't this come up before you switched to Postgresql? There are a variety of potential reasons, but it probably has to do with how the previous database was setup vs how the Postgresql database was set up (manually vs Django migrations?).

It may also have to do with whether or not you changed where these things are being stored. Did you change your MEDIA settings so the paths where files are stored got a lot longer?

What you really should be doing is looking directly at your database. Open up a psql instance and ask it to describe your tables for you. It'll tell you which fields are limited to 100 characters and those are the fields giving you problems.

这篇关于值太长的类型字符变化(100)----最近切换数据库,在db中没有做任何事情的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆