简体   繁体   中英

Migrate Django / MySQL foreign key to accept null values

Have a Django / MySQL set up. There's a model, Survey, which currently looks like...

class Survey(models.Model):

    company = models.ForeignKey('Company')

I want to set up the model, so company can be a null value:

    company = models.ForeignKey('Company', blank = True, null = True)

However, I'm not sure what I should do on the MySQL side to ensure all the existing constraints / models. Do I just alter the column through the console to accept null values? It's a live database, so I don't want to experiment too much (my development environment uses SqlLite3).

Update your model so that blank=True, null=True . Then run the sqlall command on your production server (so that it gives the output for MySQL)

./manage.py sqlall myapp

Find the create table statement This will show the new definition for the survey_id field.

CREATE TABLE `myapp_survey` (
...
`survey_id` integer
...

Then, in your database shell, modify the column to accept null values using the ALTER TABLE command.

ALTER TABLE myapp_survey MODIFY company integer;

Be careful, and consider whether you want to run MySQL in your development environment as well. Do you really want to be copying and pasting commands from Stack Overflow into your live DB shell without testing them first?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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