Django TypeError:id()正好接受一个参数(给定0)

时间:2018-08-23 06:10:06

标签: python mysql django

因此,我一直在尝试实现一种将多个图像上传到帖子的方法。我这样做的方法是拥有桌子。一张用于实际帖子,另一张用于上传图片。我打算将它们与外键链接,但无法正常工作。我的终端开始抛出错误“ TypeError:id()恰好接受一个参数(给定0)”。每当我迁移它时,都会抛出此错误。

我不确定该如何解决。

我的代码:

models.py

from django.db import models
from django.utils import timezone
from django.forms import ModelForm
from django.utils.text import slugify
from django.utils.crypto import get_random_string
from django.conf import settings

from PIL import Image

import os

DEFAULT_IMAGE_ID = 1

# Create your models here.
class Projects(models.Model):
    title = models.CharField(max_length=30)
    description = models.TextField(max_length=150)
    publish_date = models.DateTimeField(auto_now=False, auto_now_add=True)
    update_date = models.DateTimeField(auto_now=True, auto_now_add=False)
    slug = models.SlugField(unique=True)
    files = models.FileField(upload_to='files/', blank=True)
    images = models.ImageField(upload_to='images/', height_field = 'img_height', width_field = 'img_width',blank=True)
    img_height = models.PositiveIntegerField(default=600)
    img_width = models.PositiveIntegerField(default=300)
    #feature_images = models.ForeignKey(P_Images, on_delete=models.CASCADE, default=DEFAULT_IMAGE_ID)
    feature_images = models.AutoField(primary_key=True)

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        # Generates a random string 
        unique_string = get_random_string(length=32)

        # Combines title and unique string to slugify
        slugtext = self.title + "-" + "unique_id=-" + unique_string
        self.slug = slugify(slugtext)

        return super(Projects, self).save(*args, **kwargs)

class P_Images(models.Model):
    p_file = models.ImageField(upload_to='images/', blank=None)
    p_uploaded_at = models.DateTimeField(auto_now_add=True, auto_now=False)
    #fk_post = models
    fk_post = models.ForeignKey(Projects, on_delete=models.CASCADE)

错误日志

Operations to perform:
  Apply all migrations: admin, auth, contenttypes, projects, sessions
Running migrations:
  Applying projects.0005_auto_20180823_0553...Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute
    output = self.handle(*args, **options)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 200, in handle
    fake_initial=fake_initial,
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/migrations/migration.py", line 122, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/erichardson/env01/lib/python3.6/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/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 525, in alter_field
    old_db_params, new_db_params, strict)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 630, in _alter_field
    new_default = self.effective_default(new_field)
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 218, in effective_default
    default = field.get_default()
  File "/home/erichardson/env01/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 775, in get_default
    return self._get_default()
TypeError: id() takes exactly one argument (0 given)

我为此使用MySQL数据库。更新表以使其能够相互链接后,此错误开始弹出。我计划将P_Images的fk_post包含外键的Projects的feature_image值。

005_migration.py

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


class Migration(migrations.Migration):

    dependencies = [
        ('projects', '0004_auto_20180823_0547'),
    ]

    operations = [
        migrations.AlterField(
            model_name='p_images',
            name='fk_post',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='projects.Projects'),
        ),
        migrations.AlterField(
            model_name='projects',
            name='feature_images',
            field=models.IntegerField(default=builtins.id),
        ),
    ]

请让我知道migration.py是否告诉您什么或什么。

2 个答案:

答案 0 :(得分:0)

您的迁移过程中有些奇怪的事情:

models.IntegerField(default=builtins.id)

这是指内置的id函数,该函数需要一个参数,因为它返回Python中对象的内部ID。它与数据库ID无关,并且根本不属于数据库ID。我只能猜测在创建迁移时要求您提供默认设置,而您只是输入了id

您应该从迁移中删除该默认值,但这可能使其无法执行。您也可以尝试使用默认的0,在这里很有意义。但是您的实际模型代码显示该字段为主键,因此您可能需要进行另一个后续迁移,从而再次更改该字段;和0不能作为pk。

如果您仍在开发中,并且没有任何需要保留的数据,我建议您完全删除数据库和迁移,并从makemigrations重新开始。

答案 1 :(得分:-1)

我认为发生此错误的原因是您尚未为外键设置默认值。对于您以前的P_Images实例(在当前迁移之前),它们没有与之相关的Projects ID。 显示的错误文本也确认了这一点:

return self._get_default()
TypeError: id() takes exactly one argument (0 given)

因此,请尝试添加默认值:

DEFAULT_PROJECT = 1 # or the id of any project that does exist
fk_post = models.ForeignKey(Projects, on_delete=models.CASCADE, default = DEFAULT_PROJECT)