0

我有 Django 模型:

#models.py

class m1(models.Model):
    some_word = models.CharField()

我已经使用“manage.py syncdb”命令创建了 db,然后将 ForeignKey 字段添加到模型中

#models.py

from django.contrib.auth.models import User
class m1(models.Model):
    some_word = models.CharField()
    user = models.ForeignKey(User)

据我所知,原生django不提供数据库修改,所以我需要手动创建列'user_id'。好的,我去 phpmyadmin 并创建此列。此时一切正常,应用程序正常工作。但后来我明白我需要在用户字段中选择“空白=真”:

#models.py

from django.contrib.auth.models import User
class m1(models.Model):
    some_word = models.CharField()
    user = models.ForeignKey(User, blank = True)

在保存任何 m1 对象时,我收到错误“无法分配无:“m1.user”不允许空值”。我知道如果我删除表并使用syncdb创建它,一切都会好起来的,如果我使用像South这样的迁移工具,它也可以。但我想了解这个机制并找出 db 有什么问题。

我调用“manage.py sqlall app”,它告诉“CREATE TABLE”并创建索引:

CREATE INDEX `app_m1_a703c35a` ON `app_m1` (`user_id`);

ALTER TABLE `app_m1` ADD CONSTRAINT `user_id_refs_id_5b1b34cc` 
FOREIGN KEY (`user_id`) REFERENCES `auth_user` (`id`);

好的,我去 phpmyadmin 做这个 sql 的东西(坦率地说,我不知道这些索引是做什么的)。但是错误仍然存​​在。我应该怎么办?

4

1 回答 1

0

Firstly, you should use South to do these database migrations for you, especially as you admit you don't really understand what's going on.

Secondly, the error is not because it's missing blank=True, but because it's missing null=True, which is a completely different thing. The documentation explains this well.

于 2012-08-07T15:57:58.370 回答