如何使用 Django Shell 在 SQLITE3 中删除 table 行?
how to delete row of table in SQLITE3 using Django Shell?
在练习将 sqlite3 与 django 结合使用时,我通过 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)>]>
现在我设置一个名为 flights 的变量来存储查询:
# 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
。
我发现这种情况发生时,这是最简单的方法。如果您的数据库中有数据需要保留,请不要这样做。
运行 下面的命令,问题就解决了:
Flight.objects.filter(id=id).delete()
其中:(id) 是您要删除的元组的 ID
在练习将 sqlite3 与 django 结合使用时,我通过 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)>]>
现在我设置一个名为 flights 的变量来存储查询:
# 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
。
我发现这种情况发生时,这是最简单的方法。如果您的数据库中有数据需要保留,请不要这样做。
运行 下面的命令,问题就解决了:
Flight.objects.filter(id=id).delete()
其中:(id) 是您要删除的元组的 ID