首页 > 解决方案 > 返回 DateTimeField 会导致 OperationError

问题描述

from django.db import models

# Create your models here.
class TheDate(models.Model):
    """A topic the user is learning about"""
    theDate = models.DateTimeField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """returns a string representation of the model"""
        return self.theDate

即使尝试访问值存储或尝试保存新字段也会导致以下回溯:

OperationalError at /admin/meal_plans/thedate/
no such table: meal_plans_thedate
Request Method: GET
Request URL:    http://localhost:8000/admin/meal_plans/thedate/
Django Version: 2.2
Exception Type: OperationalError
Exception Value:    
no such table: meal_plans_thedate
Exception Location: C:\Users\$$$\Desktop\meal_planner\ll_env\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 383
Python Executable:  C:\Users\$$$\Desktop\meal_planner\ll_env\Scripts\python.exe
Python Version: 3.8.3
Python Path:    
['C:\\Users\\$$$\\Desktop\\meal_planner',
 'C:\\Program '
 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\\python38.zip',
 'C:\\Program '
 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\\DLLs',
 'C:\\Program '
 'Files\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_3.8.1008.0_x64__qbz5n2kfra8p0\\lib',
 'C:\\Users\\$$$\\AppData\\Local\\Microsoft\\WindowsApps\\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0',
 'C:\\Users\\$$$\\Desktop\\meal_planner\\ll_env',
 'C:\\Users\\$$$\\Desktop\\meal_planner\\ll_env\\lib\\site-packages']
Server time:    Sun, 28 Jun 2020 13:18:06 +0000

标签: pythondjango

解决方案


该错误表示您没有正确迁移模型。您需要运行manage.py makemigrationsmanage.py migrate迁移数据库,以便它在数据库端创建表。

此外__str__应该返回一个string 对象,例如,您可以str(…)调用self.theDate

from django.db import models

# Create your models here.
class TheDate(models.Model):
    """A topic the user is learning about"""
    theDate = models.DateTimeField()
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        """returns a string representation of the model"""
        return str(self.theDate)

推荐阅读