简体   繁体   English

为什么不能在review表中插入数据?

[英]Why can't insert data in the review table?

The error mentions that a violation of foreign key constraints.该错误提到违反外键约束。

MY ERROR: sqlalchemy.exc.IntegrityError: (psycopg2.errors.ForeignKeyViolation) insert or update on table "reviews" violates foreign key constraint "reviews_book_id_fkey" DETAIL: Key (book_id)=(770) is not present in table "reviews".我的错误:sqlalchemy.exc.IntegrityError:(psycopg2.errors.ForeignKeyViolation)在表“reviews”上插入或更新违反了外键约束“reviews_book_id_fkey”详细信息:键(book_id)=(770)在表“reviews”中不存在。

MY QUERY:我的查询:

db.execute("INSERT INTO reviews (comment, score, user_id, book_id) VALUES (:comment, :score, :user_id, :book_id)", {"comment":comment, "score": score, "user_id": user.id, "book_id": book_id})
    db.commit()

MY TABLES:我的桌子:

评论表

书桌

在此处输入图像描述

UPDATE: The books in the table "books" do exist!更新:表“书”中的书确实存在!

In case the problem may be in the populating process, here is a piece of code on how I populated the "books" table:如果问题可能出在填充过程中,这里有一段关于我如何填充“书籍”表的代码:

f = open("books.csv") 
reader = csv.reader(f) 
for isbn, title, author, year in reader: 
   if year != 'year': 
      db.execute("INSERT INTO books (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)", {"isbn": isbn, "title": title, "author": author, "year": year}) 
db.commit()

UPDATE #2: here is a snapshot of my table "books" and the ID is visible:更新#2:这是我的表“书”的快照,ID 是可见的:

数据库选择书籍表

I finally did some research and solved it, it turned out I was using postgreSQL, and I am newbie.我终于做了一些研究并解决了它,原来我使用的是postgreSQL,我是新手。 so I looked at the postgreSQL syntax and I decided to drop my review table and create it again.所以我查看了 postgreSQL 语法,我决定放弃我的审查表并重新创建它。 This first piece of code is how I CREATED my old table (the one that didn't work)这第一段代码是我如何创建我的旧表(那个不起作用的)

CREATE TABLE reviews(
 id SERIAL PRIMARY KEY,
 score INTEGER NOT NUL,
 comment VARCHAR NOT NULL,
 user_id INTEGER REFERENCES users, #HERE WAS THE MISTAKE 
 book_id INTEGER REFERENCES books) #AND HERE AGAIN THE MISTAKE

So as you can see I forgot to add the id column to the tables:如您所见,我忘记将 id 列添加到表中:

CREATE TABLE reviews(
 id SERIAL PRIMARY KEY,
 score INTEGER NOT NUL,
 comment VARCHAR NOT NULL,
 user_id INTEGER REFERENCES users(id),  # AND HERE I FIXED IT
 nook_id INTEGER REFERENCES books(id))  # AND HERE TOO

Simple mistake but it took me a while to figure it out.一个简单的错误,但我花了一段时间才弄清楚。 Like I said always read the docs and check if the syntax is right, my mistake here was to assume that referencinf to the table would be enough, and that would take the id as default foreign key.就像我说的总是阅读文档并检查语法是否正确,我在这里的错误是假设对表的引用就足够了,并且会将 id 作为默认外键。 Never assume, lesson learned.永远不要假设,吸取教训。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM