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

2024-04-27 19:19:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Ubuntu 14.04.5上用Python 3.4运行Django 1.11

将我的开发代码移动到测试服务器并遇到一些奇怪的错误。有人能从回溯中看出什么不对吗?

我对linux很陌生,在第一次使用Windows机器时犯了一个错误。此后,我创建了一个测试服务器和生产服务器的virtualbox副本以供开发,但我希望现在可以挽救测试服务器上的问题。

我认为我的应用程序正在为这个环境寻找正确的目录,但是我是一个Django、Python和linux noob。

任何方向都会很有帮助。

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

谢谢! 员工经理/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)

迁移员工经理0003 U auto U 20180131 U 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"

Tags: djangonameinpyselfenvtruedb
2条回答

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

这个问题可能与Django中的this open bug有关。其中一个字段中有一些测试数据,您现在正在将其转换为外键。

例如,也许department过去是一个CharField,您添加了一个雇员,该雇员的department值是“test”。现在您正试图将department从CharField更改为ForeignKey。问题是Django试图将先前的值“test”转换为ForeignKey的关系值(整数)。

我可以想出一些好的解决方案:

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

```

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);'),
    ]

相关问题 更多 >