尝试在 Django 中迁移模型时出现值错误

Posted

技术标签:

【中文标题】尝试在 Django 中迁移模型时出现值错误【英文标题】:Value error when trying to migrate models in Django 【发布时间】:2020-08-24 08:21:10 【问题描述】:

我正在尝试在我的模型上运行迁移,但一直遇到 ValueError。

这是我的models.py:

class Vehicles(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    make = models.CharField(max_length=128)
    model = models.CharField(max_length=128)
    cover_image = models.ImageField(default='vehicle_cover_pics/default.jpg', upload_to='vehicle_cover_pics')

    class Meta:
        verbose_name = 'Vehicles'
        verbose_name_plural = 'Vehicles'

    def __str__(self):
        return f"self.user.username's self.model"

def get_image_filename(instance, filename):
    id = instance.vehicle.id
    return f"vehicle_pics/id.jpg"

class VehicleImages(models.Model):
    vehicle = models.OneToOneField(Vehicles, on_delete=models.CASCADE)
    image = models.ImageField(upload_to=get_image_filename, default=None)

    class Meta:
        verbose_name = 'Vehicle Images'
        verbose_name_plural = 'Vehicle Images'

    def __str__(self):
        return f"self.vehicle.user.username's self.vehicle.model Image"

当我尝试迁移模型时,出现以下错误:

C:\Users\T Smith\Documents\Python\garage>python manage.py migrate
Operations to perform:
  Apply all migrations: accounts, admin, auth, contenttypes, home, sessions
Running migrations:
  Applying accounts.0021_auto_20200508_1328... OK

  Applying home.0002_auto_20200507_1905...Traceback (most recent call last):
  File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 1768, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: 'None'

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

Traceback (most recent call last):
  File "manage.py", line 21, in <module>
    main()
  File "manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line
    utility.execute()
  File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\core\management\base.py", line 369, in execute
    value = self.get_prep_value(value)
  File "C:\Users\T Smith\Anaconda3\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value
    ) from e
ValueError: Field 'id' expected a number but got 'None'.

我认为这与我用来将多个图像绑定到一个“车辆”实例的“get_image_filename”函数有关。

现在模型中没有存储数据,所以它在尝试运行时可能会返回错误?也许我需要找到一种方法让该函数仅在数据可用时运行?

我对这些东西很陌生,所以任何帮助都将不胜感激。谢谢!

更新: 这是我认为模型的初始迁移文件。此后,我将 ForiegnKey 字段更改为 OneToOne。

import accounts.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('accounts', '0011_auto_20200422_1529'),
    ]

    operations = [
        migrations.CreateModel(
            name='Vehicles',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('make', models.CharField(max_length=128)),
                ('model', models.CharField(max_length=128)),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='VehicleImages',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('image', models.ImageField(upload_to=accounts.models.get_image_filename)),
                ('vehicle', models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, to='accounts.Vehicles')),
            ],
        ),
    ]

这里是 0021_auto_20200508_1328.py 的迁移:

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


class Migration(migrations.Migration):

    dependencies = [
        ('accounts', '0020_auto_20200508_1317'),
    ]

    operations = [
        migrations.AlterField(
            model_name='vehicleimages',
            name='image',
            field=models.ImageField(default=None, upload_to=accounts.models.get_image_filename),
        ),
    ]

【问题讨论】:

可以分享一下相关的迁移文件吗? 我不确定该怎么做。看起来我的应用程序的 Migrations 文件夹中有很多不同的文件。让我看看我是否能弄清楚如何上传文件夹 但是错误在迁移accounts.0021_auto_20200508_1328,所以有问题的迁移文件位于accounts/migration/0021_auto_20200508_1328.py 好的,我明白你在说什么,刚刚贴在上面。 在您的VehicleImages 模型中,您有一个名为imageForeignKey,带有一个default=None,但该字段不可为空(因为您没有指定null=True)。您可以使其为空(并删除您所做的迁移并创建新的迁移)。 【参考方案1】:

删除所有迁移并将现场车辆的 修改为models.ForeignKey(Vehicles, on_delete= models.CASCADE)。 它应该可以工作。

【讨论】:

【参考方案2】:

您说:“也许我需要找到一种方法让该函数仅在数据可用时运行?”

为此

if instance.vehicle.id is not None
   id = instance.vehicle.id
   return f"vehicle_pics/id.jpg"

这将达到目的。但是如果你还是想初始化它,你能分享一下迁移文件吗?

【讨论】:

我不确定该怎么做。看起来我的应用程序的 Migrations 文件夹中有很多不同的文件。让我看看我是否能弄清楚如何上传文件夹

以上是关于尝试在 Django 中迁移模型时出现值错误的主要内容,如果未能解决你的问题,请参考以下文章

运行 make 迁移时出现 Django 关系错误

在 Heroku 上部署时出现 Django 1.7 迁移错误

使用 SVM 对多维输出类进行分类时出现值错误

使用查询数据库的默认字段函数迁移时出现 Django 错误

使用python 3创建字典时出现值错误

尝试迁移 Laravel 数据库时出现错误