python - 如何使用 Django Shell 删除 SQLITE3 中的表行?
问题描述
在练习使用 django 的 sqlite3 时,我通过 Django Shell 创建了一行:
# Import our flight model
In [1]: from flights.models import Flight
# Create a new flight
In [2]: f = Flight(origin="New York", destination="London", duration=415)
# Instert that flight into our database
In [3]: f.save()
# Query for all flights stored in the database
In [4]: Flight.objects.all()
Out[4]: <QuerySet [<Flight: Flight object (1)>]>
现在我设置了一个名为航班的变量来存储查询:
# Create a variable called flights to store the results of a query
In [7]: flights = Flight.objects.all()
# Displaying all flights
In [8]: flights
Out[8]: <QuerySet [<Flight: 1: New York to London>]>
# Isolating just the first flight
In [9]: flight = flights.first()
现在在models.py中我做了以下事情:
class Airport(models.Model):
code = models.CharField(max_length=3)
city = models.CharField(max_length=64)
def __str__(self):
return f"{self.city} ({self.code})"
class Flight(models.Model):
origin = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="departures")
destination = models.ForeignKey(Airport, on_delete=models.CASCADE, related_name="arrivals")
duration = models.IntegerField()
def __str__(self):
return f"{self.id}: {self.origin} to {self.destination}"
运行迁移后:
# Create New Migrations
python manage.py makemigration
# Migrate
python manage.py migrate
我收到以下错误,因为我需要删除从纽约到伦敦的现有航班以支持新结构,但是,我不知道该怎么做......
这是错误:
python manage.py migrate
System check identified some issues:
WARNINGS:
?: (urls.W005) URL namespace 'flights' isn't unique. You may not be able to
reverse all URLs in this namespace
Operations to perform:
Apply all migrations: admin, auth, contenttypes, flights, sessions
Running migrations:
Applying flights.0002_auto_20210530_1202...Traceback (most recent call last):
File "C:\Users\kaij\Documents\cs50\airline\manage.py", line 22, in <module>
main()
File "C:\Users\kaij\Documents\cs50\airline\manage.py", line 18, in main
execute_from_command_line(sys.argv)
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
utility.execute()
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
self.execute(*args, **cmd_options) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute
output = self.handle(*args, **options)
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped
res = handle_func(*args, **kwargs) File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
post_migrate_state = executor.migrate(
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py",
line 117, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py",
line 147, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py",
line 230, in apply_migration
migration_recorded = True
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 35, in __exit__
self.connection.check_constraints()
File "C:\Users\kaij\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\base.py", line 353, in check_constraints, line 353, in check_constraints
raise IntegrityError( w in table 'flights_flight' with primary key '1' has an invalid foreign k
django.db.utils.IntegrityError: The rots_flight.origin_id contains a value 'New Yoesponding value in flights_aiw in table 'flights_flight' with prima value in flights_airport.id.ry key '1' has an invalid foreign key:e> flights_flight.origin_id contains a value 'New York' that does not have a corresponding value in flights_airport.id.
PS C:\Users\kaij\Documents\cs50\airline>
我尝试在 Django shell 中输入:
flight.delete
flight.delete()
它仍然没有删除该行谢谢
解决方案
由于您只是在练习并且当前数据库中数据的完整性并不重要,我建议您执行以下操作:
- 删除
db.sqlite3
项目根目录中的文件。 - 在您的应用程序中找到
migrations
航班模型所在的文件夹,然后删除其中的所有文件,除了__init__.py
. - 跑来
python manage.py makemigration
跑去python manage.py migrate
。
当这种情况发生时,我发现这是最简单的方法。不要在您需要保留数据库中的数据的情况下执行此操作。
推荐阅读
- html - Grails 和 HTML 编码
- php - 如何使用链接到 php 的 python 修复没有输出?
- wordpress - 如何修复 wp-admin 没有出现在 wordpress 中的 url 问题?
- c# - 具有下拉问题的引导表单组
- c - 为什么在调试模式下会得到不同的值?
- php - auth_type=reauthenticate(in FB login URL) 如果用户以前登录过,则不要求用户输入密码。我正在使用 PHP SDK
- javascript - UnhandledPromiseRejectionWarning 随机发生
- api - 在 Google Analytics(分析)用户活动报告 API 中,JSON 响应中 1 的采样大小是什么意思?
- javascript - 组合图 - 带条形图的字图
- javascript - 我正在尝试使用opencv.js(javascript)检测蓝色的矩形纸