gpt4 book ai didi

python - psycopg2 psycopg2.InternalError 依赖对象

转载 作者:行者123 更新时间:2023-11-29 13:34:33 24 4
gpt4 key购买 nike

我在 heroku 上使用 peewee,但根据 peewee 文档,删除相关表必须在代码中完成。

问题是如何?

我有以下型号

class WebPage(Model):
title = CharField()

class Term(Model):
name = CharField()

class WebPageTerms(Model):
term = ForeignKeyField(Term)
webpage = ForeignKeyField(WebPage)

包含postgresql自定义语句的drop table方法:

def drop_tables():
WebPage.drop_table(fail_silently=True)
Term.drop_table(fail_silently=True)
WebPageTerms.drop_table(fail_silently=True)

作为部署的一部分,我删除所有表并创建它们以添加新字段。

我试过以下方法,但还是不行:

conn = psycopg2.connect("dbname='' user='' host='' password=''")
curr = conn.cursor()
curr.execute("DROP table webpageterms CASCADE")
curr.execute("DROP table webpage CASCADE")
curr.close()
conn.close()

但我总是得到同样的错误

psycopg2.InternalError: cannot drop table webpage because other objects depend on it DETAIL: constraint webpageterms_webpage_id_fkey on table webpageterms depends on table webpage HINT: Use DROP ... CASCADE to drop the dependent objects too.

我怎样才能删除这些表?

** 编辑 **试图将代码更改为:

curr.execute("ALTER TABLE webpageterms DROP CONSTRAINT webpageterms_webpage_id_fkey")

但我得到:

psycopg2.InternalError: cannot drop table webpage because other objects depend on it
DETAIL: constraint webpageterms_webpage_id_fkey on table webpageterms depends on table webpage
HINT: Use DROP ... CASCADE to drop the dependent objects too.

最佳答案

按以下顺序放置它们:

WebPageTerms.drop_table(fail_silently=True)
Term.drop_table(fail_silently=True)
WebPage.drop_table(fail_silently=True)

Peewee 带有一个删除表的帮助程序——它通过遵循外键为您按拓扑对它们进行排序:

from peewee import drop_model_tables
drop_model_tables([WebPage, Term, WebPageTerms]) # <-- will sort them correctly

关于python - psycopg2 psycopg2.InternalError 依赖对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16261170/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com