Django:无法为User添加foreight键

时间:2016-06-14 17:05:26

标签: python django ldap django-migrations

我正在使用ldap进行身份验证,就像Understanding Django-LDAP authentication一样。

我的模特是:

class MyFile(models.Model):
    file = models.FileField(upload_to="files")
    slug = models.SlugField(max_length=50, blank=True)
    user = models.ForeignKey(User, unique=True)

但我无法进行迁移:

python src/manage.py makemigrations
You are trying to add a non-nullable field 'user' to myfile without a default;
we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option: 

然后我输入datetime.date.today()并运行python manage.py migrate 错误是:

  File "/usr/local/lib/python2.7/dist-packages/django/db/models/fields/__init__.py", line 915, in get_prep_value
    return int(value)
TypeError: int() argument must be a string or a number, not 'datetime.date'

有什么想法吗?感谢

更新

class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
    migrations.CreateModel(
        name='MyFile',
        fields=[
            ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
            ('file', models.FileField(upload_to='files')),
            ('slug', models.SlugField(blank=True)),
            ('user', models.ForeignKey(User, blank=True, null=True)),
        ],
    ),
]

错误:

ValueError: Lookup failed for model referenced by field fileupload.MyFile.user: auth.User

1 个答案:

答案 0 :(得分:1)

您需要为所有现有文件提供默认用户ID 。它必须是现有的用户ID和整数。它不能是datetime.date

或者,如果适用,您可以将文件 - >用户链接设为可选

user = models.ForeignKey(User, blank=True, null=True)