python - model.py 更改后 Django 站点预览未更新

标签 python django django-models

我正在学习 django,并且正在研究模型。我创建了一个产品类

from django.db import models


class Product(models.Model):
    title = models.CharField(max_length=10)
    description = models.TextField(blank=False)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    featured = models.BooleanField(default=False)
    int = models.IntegerField(default=10)

我正在尝试删除“int”字段,但 django 站点没有更新 更改后。

删除模型字段(“int”字段,请参阅屏幕截图)后, 并运行

python manage.py makemigrations

python manage.py migrate

实时预览不会更新并引发有关已删除字段的错误。关闭服务器并重新启动服务器后(ctrl + c 并比 python manage.py runserver 页面更新并且不会抛出任何错误

我正在使用sqlite。我尝试删除 'pycache' 并且所有迁移也是 db.sql3,重新创建 super 用户,但删除任何字段后我仍然遇到相同的错误。

图片1 -> 初始状态$ https://ibb.co/Yb6pmgr 图片 2 -> 删除“int”字段后 https://ibb.co/xf1bJQJ 图片 3 -> 错误:$ https://ibb.co/0cPyRZv

最佳答案

首先停止您的服务器,然后进行更改并运行 python manage.py makemigrationspython manage.py migrate 命令。也许这会起作用,但你正在使用 Python 中的保留关键字。

如果它不起作用,现在只需删除位于 trydjango/src/products/migrations/ 路径上的 0001_initial.py 即可。如果您的数据库中已有一些数据,请备份某处。 intBuilt-in Functions 之一在Python中。请不要在 Python 中到处使用这样的命名约定。看看下面的例子,你就会有所了解。

str_val = '1'

print(str_val)  # 1
print(type(str_val))  # <class 'str'>

int_val = int(str_val)

print(int_val)  # 1
print(type(int_val))  # <class 'int'>

这只是一个使用 int() 将字符串值转换为整数值的简单示例。让我们为 int() 分配一些值.

# by default
print(int)  # <class 'int'>
print(type(int))  # <class 'type'>

# let's get the previous example again
str_val = '1'

print(str_val)  # 1
print(type(str_val))  # <class 'str'>

# assign some value to int(). (please please please never do such a thing like this)
int = 'assigned string'
print(int)  # 'assigned string'
print(type(int))  # <class 'str'>

int_val = int(str_val)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

当你执行上面的代码时,你会得到这样的错误。所以int()不会进一步将字符串转换为整数。因为你违反了规则。现在它就像一个普通变量一样。不过,如果您确实想添加像 int 这样的变量,只需使用 _intint_ 并且如果您想将列名称显示为 int 只需添加 db_column 名称即可。

_int = models.IntegerField(default=10, db_column='int')

# or

int_ = models.IntegerField(default=10, db_column='int')

在进行这些更改之前,请停止您的服务器。然后进行编辑,然后运行python manage.py makemigrationspython manage.py migrate。希望这个答案能对您有所帮助。

更新:

这个answer将帮助您找到 Python 中的所有保留关键字,并且不要使用其中任何一个作为变量名称。

关于python - model.py 更改后 Django 站点预览未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56730548/

相关文章:

python - 根据关联的 id 在 `master_order` 数组中的位置重新排序 numpy 数组

python - Django: 'module' 对象没有属性 'index'

python - Django - 模板渲染性能(我认为)如何检查启用 LocMemCache 是否有效?

python - 渲染默认图像,Django

python - 如何在 django html 中导入模块?

Python tarfile : how to use tar+gzip compression with follow symbolic link?

python - 小于最大值的所有因子产品的枚举

python - 参数化 Tornado RequestHandler

python - Django:你能在管理站点上传一个目录或多个文件吗

django - i18n Django 国际化和数据库对象