【问题标题】:how to delete row of table in SQLITE3 using Django Shell?如何使用 Django Shell 删除 SQLITE3 中的表行?
【发布时间】:2021-08-18 03:30:47
【问题描述】:

在练习使用 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)>]>

现在我设置了一个名为航班的变量来存储查询:

# 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()

它仍然没有删除该行 谢谢

【问题讨论】:

    标签: python django sqlite cs50


    【解决方案1】:

    运行以下命令,问题就解决了:

    Flight.objects.filter(id=id).delete()


    其中:(id) 是您要删除的元组的 id

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    【解决方案2】:

    由于您只是在练习,当前数据库中数据的完整性并不重要,我建议您执行以下操作:

    • 删除项目根目录下的db.sqlite3 文件。
    • 在您的应用中找到航班模型所在的 migrations 文件夹,然后删除其中除 __init__.py 之外的所有文件。
    • 再次运行 python manage.py makemigrationpython manage.py migrate

    当这种情况发生时,我发现这是最简单的方法。如果您的数据库中有您需要保留的数据,请不要这样做。

    【讨论】:

    • 谢谢这是一个简单的解决方案:)
    • 很高兴我能帮忙?
    猜你喜欢
    • 2011-01-18
    • 2019-06-12
    • 2020-08-31
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 2015-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多