应用Django迁移时,“ TypeError:int()参数必须是字符串”

时间:2019-11-10 02:07:01

标签: django django-models django-migrations

我遇到以下错误:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'EventCategory'

当尝试应用django创建的迁移时。

由于迁移是自动生成的文件,所以我试图恢复迁移并再次运行makemigration,但这是行不通的。

有关更多信息...

型号:

class Event(models.Model):
    name = models.CharField(max_length=100)
    longitue = models.DecimalField(max_digits=9, decimal_places=6)
    latitude = models.DecimalField(max_digits=9, decimal_places=6)
    from_datetime = models.DateTimeField()
    to_datetime = models.DateTimeField(blank=True, null=True)
    main_category = models.ForeignKey('even.EventCategory', 
                            default=EventCategory.get_default_category, 
                            on_delete=models.SET_DEFAULT)
    subcategories = models.ManyToManyField('even.EventCategory', related_name='subcategories')

迁移:

# Generated by Django 2.2.6 on 2019-11-10 01:44
class Migration(migrations.Migration):

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('even', '0005_eventcategory_default'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='subcategories',
            field=models.ManyToManyField(related_name='subcategories', to='even.EventCategory'),
        ),
        migrations.AlterField(
            model_name='event',
            name='main_category',
            field=models.ForeignKey(default=apps.even.models.eventCategory.EventCategory.get_default_category, on_delete=django.db.models.deletion.SET_DEFAULT, to='even.EventCategory'),
        ),
    ]

跟踪:

Running migrations:
  Applying even.0006_auto_20191110_0144.../usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py:1423:
Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/related.py", line 937, in get_db_prep_save
    return self.target_field.get_db_prep_save(value, connection=connection)
  File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 789, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 959, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/usr/local/lib/python3.7/site-packages/django/db/models/fields/__init__.py", line 968, in get_prep_value
    return int(value)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'EventCategory'TypeError: int() argument must be a string, a bytes-like object or a number, not 'EventCategory'

1 个答案:

答案 0 :(得分:0)

我怀疑EventCategory.get_default_category方法返回了模型实例。 default字段的ForeignKey必须作为字段而不是模型实例返回。

因此请确保您的EventCategory.get_default_category返回类别pk