Error around foreign key constraint when post method is performed in flash

Asked 2 years ago, Updated 2 years ago, 106 views

When I tried to implement the POST method while creating the API in flash, I encountered the following error, but I am having trouble solving it.

  • Error Contents
sqlalchemy.exc.IntegrityError: (_mysql_exceptions.IntegrityError) (1452, 'Cannot add or update a child row: a foreign key constraint fails (`mydb`.`page`, CONSTRAINT `page_ibfk_1` FOREIGN KEY (`belong_id`) REFERENCES `belong` (`id`))') [SQL: 'INSERT INTO page (id, title, belong_id, created_at, updated_at) VALUES (%s, %s, %s, %s, %s)'] [parameters: (0, 'test', '', datetime.datetime(2019, 1, 2, 6, 16, 56, 752822), datetime.datetime (2019, 1, 2, 6, 16, 56, 752822))] (Background on this error at: http://sqlalche.me/e/gkpj)
127.0.0.1 - [02/Jan/2019 06:16:56] "POST/pages?title=test HTTP/1.1"500-
  • flask POST method implementation part
@ app.route('/pages', methods=['POST'])
def post_page():
    title=request.args.get('title',')
    belong_id = request.args.get('belong_id',')
    page_repository=PageRepository(access_point)
    page=page_repository.post(title,belong_id)
  • What to do
 curl-X POST-H "Content-Type: application/json" http://0.0.0:8080/pages?belong_id=1&title=test
  • o/r Mapper Partial Excerpt
Class Relationship (Base):
    __tablename__='relationship'
    id=Column('id', Integer, primary_key=True)
    code_link = Column ('code_link', Text)
    memo = Column ('memo', Text)

class Belong (Base):
    __tablename__='belong'
    id=Column('id', Integer, primary_key=True)
    relationship_order=Column('relationship_order', Integer, ForeignKey('relation.id', onupdate="CASCASE',ondelete="CASCASE"))
    page=relationship('Page')

Base.metadata.create_all(engine)

Class Page (Base):
    __tablename__='page'
    id=Column('id', Integer, primary_key=True)
    title=Column('title', String(200))
    belong_id=Column('belong_id', Integer, ForeignKey('belong.id', onupdate="CASCASE',ondelete="CASCASE"))
    created_at=Column(DateTime)
    updated_at=Column(DateTime)

The relationship table and the Belong table already contain one record (id=1) data.
Also, I deleted the table, remade it, and re-entered the data, but the same error occurred.

I'm sorry, but I'd appreciate it if you could tell me something.
Thank you for your cooperation.

mysql api flask

2022-09-30 11:29

1 Answers

As far as the error is concerned, the following query has been issued:

INSERT INTO page(
    id, 
    title, 
    belong_id, 
    created_at, 
    updated_at
) 
VALUES(
    0, 
    'test', 
    '',        # This is the sky
    '2019 01/02 ...',
    '2019 01/02 ...'
);

The belong_to value is empty and violates MySQL foreign key constraints, so INSERT cannot be done.


2022-09-30 11:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.