django psycopg2.DataError:整数输入语法无效:“test”将代码移动到测试服务器时出错

e5njpo68  于 2023-10-21  发布在  Go
关注(0)|答案(6)|浏览(112)

我在Ubuntu 14.04.5上运行Django 1.11和Python 3.4
将我的开发代码移动到测试服务器并遇到一些奇怪的错误。有谁能从traceback中看出什么问题吗?
我对Linux非常陌生,第一次在Windows机器上开发时犯了一个错误。我已经创建了测试和生产服务器的virtualbox副本来进行开发,但我希望现在可以挽救测试服务器上的东西。
我认为我的应用程序正在为这个环境寻找正确的目录,但我是一个Django,Python和Linux新手。
任何方向都会很有帮助。

**更新:我添加了models.py和相关应用程序的迁移。另外,我在开发机器上使用sqlite,在测试服务器上使用PostgreSQL(像个傻瓜)。

谢谢!staff_manager/models.py

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

# Create your models here.

from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from smrt.settings import DATE_INPUT_FORMATS

class OrganizationTitle(models.Model):
    def __str__(self):
        return "{}".format(self.organization_title_name)
    organization_title_name = models.CharField(max_length=150, unique=True)

class ClassificationTitle(models.Model):
    def __str__(self):
        return "{}".format(self.classification_title_name)
    classification_title_name = models.CharField(max_length=150, unique=True)

class WorkingTitle(models.Model):
    def __str__(self):
        return "{}".format(self.working_title_name)
    working_title_name = models.CharField(max_length=150, unique=True)

class Category(models.Model):
    def __str__(self):
        return "{}".format(self.category_name)
    category_name = models.CharField(max_length=150, unique=True)

class Department(models.Model):
    def __str__(self):
        return "{}".format(self.department_name)
    department_name = models.CharField(max_length=150, unique=True)

class Employee(models.Model):
    first_name = models.CharField(max_length=150)
    last_name = models.CharField(max_length=150)
    org_title = models.ForeignKey(OrganizationTitle, blank=True, null=True, on_delete=models.SET_NULL)
    manager = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL)
    manager_email = models.EmailField(max_length=50, blank=True, null=True)
    hire_date = models.DateField(blank=True, null=True)
    classification_title = models.ForeignKey(ClassificationTitle, blank=True, null=True, on_delete=models.SET_NULL)
    working_title = models.ForeignKey(WorkingTitle, blank=True, null=True, on_delete=models.SET_NULL)
    email_address = models.EmailField(max_length=250, blank=False, unique=True,
                                      error_messages={'unique': 'An account with this email exist.',
                                                      'required': 'Please provide an email address.'})
    category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.SET_NULL)
    is_substitute = models.BooleanField(default=False)
    department = models.ForeignKey(Department, blank=True, null=True, on_delete=models.SET_NULL)
    is_active = models.BooleanField(default=True)
    is_manager = models.BooleanField(default=False)

    class Meta:
        ordering = ('is_active', 'last_name',)

    def __str__(self):
        return "{}".format(self.first_name + ' ' + self.last_name)

    def __iter__(self):
        return iter([
                     self.email_address,
                     self.last_name,
                     self.first_name,
                     self.org_title,
                     self.manager,
                     self.manager.email_address,
                     self.hire_date,
                     self.classification_title,
                     self.working_title,
                     self.email_address,
                     self.category,
                     self.is_substitute,
                     self.department
                     ])

    def save(self, *args, **kwargs):
        for field_name in ['first_name', 'last_name']:
            val = getattr(self, field_name, False)
            if val:
                setattr(self, field_name, val.capitalize())
        super(Employee, self).save(*args, **kwargs)

迁移staff_manager.0003_auto_20180131_1756:

# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2018-01-31 17:56
from __future__ import unicode_literals

from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    dependencies = [
        ('staff_manager', '0002_auto_20171127_2244'),
    ]

    operations = [
        migrations.CreateModel(
            name='Category',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('category_name', models.CharField(max_length=150, unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='ClassificationTitle',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('classification_title_name', models.CharField(max_length=150, unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='Department',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('department_name', models.CharField(max_length=150, unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='OrganizationTitle',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('organization_title_name', models.CharField(max_length=150, unique=True)),
            ],
        ),
        migrations.CreateModel(
            name='WorkingTitle',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('working_title_name', models.CharField(max_length=150, unique=True)),
            ],
        ),
        migrations.AlterField(
            model_name='employee',
            name='category',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Category'),
        ),
        migrations.AlterField(
            model_name='employee',
            name='classification_title',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.ClassificationTitle'),
        ),
        migrations.AlterField(
            model_name='employee',
            name='department',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Department'),
        ),
        migrations.AlterField(
            model_name='employee',
            name='email_address',
            field=models.EmailField(error_messages={'required': 'Please provide an email address.', 'unique': 'An account with this email exist.'}, max_length=250, unique=True),
        ),
        migrations.AlterField(
            model_name='employee',
            name='first_name',
            field=models.CharField(max_length=150),
        ),
        migrations.AlterField(
            model_name='employee',
            name='hire_date',
            field=models.DateField(blank=True, null=True),
        ),
        migrations.AlterField(
            model_name='employee',
            name='last_name',
            field=models.CharField(max_length=150),
        ),
        migrations.AlterField(
            model_name='employee',
            name='manager',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.Employee'),
        ),
        migrations.AlterField(
            model_name='employee',
            name='manager_email',
            field=models.EmailField(blank=True, max_length=50, null=True),
        ),
        migrations.AlterField(
            model_name='employee',
            name='org_title',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.OrganizationTitle'),
        ),
        migrations.AlterField(
            model_name='employee',
            name='working_title',
            field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, to='staff_manager.WorkingTitle'),
        ),
    ]

回溯:

Operations to perform:
      Apply all migrations: admin, auth, contenttypes, csvimport, sessions, staff_manager
    Running migrations:
      Applying staff_manager.0003_auto_20180131_1756...Traceback (most recent call last):
      File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
        return self.cursor.execute(sql, params)
    psycopg2.DataError: invalid input syntax for integer: "test"

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
    utility.execute()
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/__init__.py", line 356, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 216, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 515, in alter_field
    old_db_params, new_db_params, strict)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/postgresql/schema.py", line 112, in _alter_field
    new_db_params, strict,
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 684, in _alter_field
    params,
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 120, in execute
    cursor.execute(sql, params)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 80, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/utils.py", line 94, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/home/www-root/envs/django_env_1/lib/python3.4/site-packages/django/db/backends/utils.py", line 65, in execute
    return self.cursor.execute(sql, params)
django.db.utils.DataError: invalid input syntax for integer: "test"

(django_env_1) www-root@Server:~/envs/django_env_1/smrt$
^C
(django_env_1) www-root@Server:~/envs/django_env_1/smrt$ django.db.utils.DataError: invalid input syntax for integer: "test"django.db.utils.DataError: invalid input syntax for integer: "test"
6ie5vjzr

6ie5vjzr1#

这个问题可能与Django中的this open bug有关。您现在要转换为ForeignKey的某个字段中有一些测试数据。
例如,可能department曾经是CharField,而您添加了一个员工,该员工的department值为“test”。现在您正在尝试将department从CharField更改为ForeignKey。问题是Django试图将之前的值“test”转换为ForeignKey的关系值(整数)。
我能想到几个好的解决办法:

  • 如果这只是一个测试数据库,只需重置数据库并在干净的数据库上运行迁移
  • 如果您需要迁移现有数据,请确定哪个字段具有“test”值。然后尝试类似于bug报告中给出的解决方案:

from future import unicode_literals

from django.db import migrations

class Migration(migrations.Migration):
dependencies = [
('documents', '0042_auto_19700101-0000'),
]

operations = [
    migrations.RunSQL('ALTER TABLE documents_document_tags ALTER tag_id TYPE varchar(32);'),
]
qcbq4gxm

qcbq4gxm2#

在我的情况下,我有同样的问题的发展。这个命令对我有用。

python manage.py flush

确保它从数据库中删除所有数据。运行此命令,它将删除数据库中的所有数据并再次运行迁移。

python manage.py migrate
eni9jsuy

eni9jsuy3#

在我的情况下,错误是thith替换IntegerField到`TextField在文件迁移
文件迁移:

# Generated by Django 3.1.3 on 2020-12-03 11:19

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('adminPanel', '0028_auto_20201203_1117'),
    ]

    operations = [
        migrations.RemoveField(
            model_name='myuser',
            name='balance',
        ),
        migrations.AlterField(
            model_name='myuser',
            name='bot_admin_chat_id',
            field=models.IntegerField(default=0),
        ),
    ]

我将IntegerField更改为TextField和python manage.py migrate
在那之后,我删除了我在模型中的专栏,做了移民和移民之后,我做了我想要的模型。

7vux5j2d

7vux5j2d4#

对我来说最简单的方法是将外键更改为字符字段,进行迁移,迁移。然后将该字段改回为外键。这样,您将强制更改数据库,这非常重要

u59ebvdq

u59ebvdq5#

在我的例子中,@YPCrumble是正确的,它是在我将一个字段从StreamField更改为CharField后引起的。
我发现的最快的解决方案是在GUI上打开我的DB(在我的情况下是Postico),并将JSON中的值覆盖为默认值。在我的情况下,这意味着将每个现有字段的值设置为1。
这使得迁移可以按预期运行,没有任何问题。

rjzwgtxy

rjzwgtxy6#

这和你的模特档案有关
你利用了Charfield,那里有Foreignkey的期望。
您可以简单地刷新数据库以清空它,然后再次迁移,它将工作。
python manage.py flush
然后
python manage.py迁移

相关问题