简体   繁体   English

当我在Django中添加ForeignKey时如何使用phpmyadmin更新数据库?

[英]How to update db with phpmyadmin when I add ForeignKey in django?

I have django model: 我有Django模型:

#models.py

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

I've made db with 'manage.py syncdb' command and then added a ForeignKey field to a model 我已经用'manage.py syncdb'命令制作了数据库,然后向模型添加了ForeignKey字段

#models.py

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

As far as I know, native django doesn't provide db modifying, so I need to create column 'user_id' manually. 据我所知,本地django不提供数据库修改功能,因此我需要手动创建列“ user_id”。 Ok, I go to phpmyadmin and create this column. 好的,我转到phpmyadmin并创建此列。 At this moment everything is ok and app works. 目前,一切正常,应用程序正常运行。 But then I understand that I need option 'blank = True' at the user field: 但是后来我了解到我需要在用户字段中使用选项“ blank = True”:

#models.py

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

And while saving any m1 object, I got error 'Cannot assign None: "m1.user" does not allow null values'. 并且在保存任何m1对象时,出现错误“无法分配无:“ m1.user”不允许空值”。 I know that if I delete table and make it with syncdb, everything will be fine, and if I use migrating tool like South, it will be ok too. 我知道,如果删除表并使用syncdb进行创建,一切都会好起来,如果我使用像South这样的迁移工具,也可以。 But I want to understand mechanics of this and find out, what is wrong with db. 但是我想了解这一点的原理,并找出db出了什么问题。

I call 'manage.py sqlall app' and it tells 'CREATE TABLE' and create indexes: 我叫“ manage.py sqlall应用程序”,它告诉“创建表”并创建索引:

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`);

Ok, I go to phpmyadmin and do this sql stuff (frankly, i don't know what these indexes do). 好的,我去phpmyadmin并做这个sql的事情(坦率地说,我不知道这些索引的作用)。 But the error is still occurs. 但是错误仍然发生。 What should I do? 我该怎么办?

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. 首先,您应该使用South来为您执行这些数据库迁移,特别是因为您承认自己并不真正了解发生了什么。

Secondly, the error is not because it's missing blank=True , but because it's missing null=True , which is a completely different thing. 其次,错误不是因为它缺少blank=True ,而是因为它缺少null=True ,这是完全不同的事情。 The documentation explains this well. 该文档对此进行了很好的解释。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM