简体   繁体   中英

How to update Django model fields in MySQL database

I created a model for posts in Django and I'm trying to update one of the fields in the database (MySQL). I have the following block of code: model.py

class Post (models.Model):
    title = models.CharField()
    preamble = models.CharField()
    body = models.TextField ()
createdAt = models.DateTimeField(auto_now_add=True, blank=True)

I want to add another field called author author=models.ForeignKey(User, on_delete=models.CASCADE Also, I want to change the name of one of the fields from preamble to introduction

Whenever I run the command python manage.py makemigrations and then python manage.py migrate , I get an error which terminates the migration process. it's telling me that the field preamble which I have in my database is not recognized. Is it possible to update preamble to introduction ?

  • Ensure you have a migration of the initial state of your app, before any modifications.
  • Rename the preamble field to introduction in your model, making no other changes.
  • Run makemigrations . It should ask you whether it was a rename.
  • Add the author foreign key.
  • Run makemigrations . It should ask you for a default for the user field if it's not nullable; 1 should hopefully refer to the first user created in your system.
  • Run migrate .

This should be work:

  1. delete the SQLite database and also migrations directory
  2. change the model
  3. then run the migrate command

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