-1

I have a models like:

from app import db
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema, fields
from datetime import datetime

class User(db.Model):
   __tablename__ = 'user'

   id = db.Column(db.Integer, db.ForeignKey('follower.followable_id'), primary_key=True)
   username = db.Column(db.String(32), nullable=False)
   email = db.Column(db.String(320), nullable=False)
   password_hash = db.Column(db.String(128), nullable=False)
   password_salt = db.Column(db.String(22), nullable=False)
   created_at = db.Column(db.DateTime, default=datetime.utcnow())

   user_comment = db.relationship('UserComment', back_populates='author')

   def to_json(self):
       return {'username': self.username, 'email': self.email}

   def get_id(self):
       return self.id


class Topic(db.Model):
   __tablename__ = 'topic'

   id = db.Column(db.Integer, db.ForeignKey('follower.followable_id'), primary_key=True)
   topic_name = db.Column(db.String(100))
   
class Follower(db.Model):
   __tablename__ = 'follower'

   id = db.Column(db.Integer, primary_key = True)
   follower_id = db.Column(db.Integer, db.ForeignKey('user.id'))
   followable_id = db.Column(db.Integer, db.ForeignKey('followable.followable_id'))

My goal is for the user to be able to follow topics and users. I tried to connect the id column of the user and topic table to the followable_id column of the follower table for this. And I linked the follower_id of the follower table to the user id.

In this case, I received an error when creating a topic table. (sqlalchemy.greetings.OperationalError: (pymysql.mistake.OperationalError) (1822, "Foreign key restriction could not be added. The missing index for the 'topic_ibfk_1' constraint in the referenced table is 'follower'")

https://stackoverflow.com/a/11618048/13975329 I took a reference from here and tried to create these tables but I couldn't.

How can I create a better design for user-topic follow mechanism and why does it give this error in topic table creation?

philipxy
  • 14,416
  • 5
  • 32
  • 77
skipsbiceps
  • 25
  • 1
  • 6
  • Ask 1 specific researched non-duplicate question. Please in code questions give a [mre]. [ask] [Help] First ask about being stuck with an error with bad code then later if stuck ask about getting to your goal with relevant parts you can do. Not both. Put everything needed but only what is needed to ask your question in your post, not just at a link. Don't expect us to read the linked page to understand what you have to say about it not helping. – philipxy Jun 03 '22 at 10:49

0 Answers0