Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

python - 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  • 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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...