gpt4 book ai didi

python - Django 的 on_delete 错误

转载 作者:太空宇宙 更新时间:2023-11-03 14:25:30 26 4
gpt4 key购买 nike

我目前正在做 Eric Matthes 所著的《Python 速成类(class)》一书中的一些项目。目前,我正在做实验 19.1,我必须使用以前的代码来制作 Django 项目,同时更改他自己的一些代码,但遇到了问题。每次我想运行这个命令

>>>python manage.py makemigration blogs

作为返回,我得到了这个代码

TypeError: init() missing 1 required positional argument: 'on_delete'

他原来的models.py代码:

from django.db import models

class Topic(models.Model):
"""A topic the user is learning about."""
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)

def __str__(self):
"""Return a string representation of the model."""
return self.text

class Entry(models.Model):
"""Something specific learned about a topic."""
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 a string representation of the model."""
return self.text[:50] + "..."

和我当前的代码:

from django.db import models

# Create your models here.

class BlogPost(models.Model):
title = models.CharField(max_length=200)
text = models.CharField(max_length=200)
date_added = models.DateTimeField(auto_now_add=True)

def __str__(self):
"""Return a string representation of the model."""
return self.text

class Post(models.Model):
"""SThe post"""
topic = models.ForeignKey(BlogPost)
text = models.TextField()
date_added = models.DateTimeField(auto_now_add=True)

class Meta:
verbose_name_plural = 'posts'

def __str__(self):
if len(self.text) >= 50:
"""Return a string represerntation of the model"""
return self.text[:50] + "..."
else:
return self.text

老实说,我不知道为什么会收到此错误代码,我已经检查过是否弄乱了某些内容,但找不到任何内容。有谁知道吗?

最佳答案

自 Django 2.x 起,on_delete是必须的。这是来自 Django 2.0 发行说明:

The on_delete argument for ForeignKey and OneToOneField is now required in models and migrations. Consider squashing migrations so that you have fewer of them to update.

因此,错误来自这一行:

topic = models.ForeignKey(BlogPost)

您正在创建外键关系,但未提供 on_delete属性(property)。因此,请点击链接并选择适合您需求的一个。

关于python - Django 的 on_delete 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47662336/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com