Django Migration Model entry prompt on delete

according to the book "python programming from introduction to practice", after modifying the models.py, execute the command python manage.py makemigrations learning_logs, to report an error and ask for advice.

model.py Code

from django.db import models
class Topic(models.Model):
    """"""
    text = models.CharField(max_length = 200)
    date_added = models.DateTimeField(auto_now_add = True)

    def __str__ (self):
        """"""
        return self.text
    
class Entry(models.Model):
    """"""
    topic = models.ForeignKey(Topic)
    text = models.TextField()
    date_added = models.DateTimeField(auto_now_add = True)

    class Meta:
        verbose_name_plural = "entries"

    def __str__(self):
        """"""
        return self.text[:50] + "..."

the manage.py code is as follows

-sharp!/usr/bin/env python
import os
import sys

if __name__ == "__main__":
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "learning_log.settings")
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn"t import Django. Are you sure it"s installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)
Mar.02,2021

two possibilities

  • topic = models.ForeignKey (Topic) one parameter on_delete. is missing Not sure which version of django you are using. How can I remember that this parameter was optional before?

https://docs.djangoproject.co.

  • makemigrations conflicts with the files in the migrations folder under your app. The solution is to delete all files in the migrations folder except _ _ init__.py. Regenerate the migrate file. At this point, however, your database table structure is generally empty, unless you can manually modify the table Django _ migrate.
in the database.

when migrating the model Entry, run the code python manage.py makemigrations learning_logs, to report an error

TypeError: _ _ init__ () missing 1 required positional argument: 'on_delete'

    :https://docs.djangoproject.com/e ... /fields/-sharpforeignkeyforeignkeyon_deletetopic = models.ForeignKey(Topic)  

topic = models.ForeignKey ('Topic', on_delete=models.CASCADE), run successfully.


because the version of django you are using is 2.x, which is mandatory for foreign keys not to declare the lower version of on_delete,. You can take a look at django's upgrade log


Django2.0, on_delete is required. Otherwise, the error will be reported, and the pycharm editor will also prompt. It is recommended that you first configure the environment to the same version as in the book.

Menu