1

I have two models in my flask app which uses sql_alchemy

The two models location and message have a one to many relationship.

class LocationModel(db.Model):
    __tablename__ = 'location'
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String)

    def __init__(self, name):
        self.name = name


class MessageModel(db.Model):
    __tablename__ = 'message'
    id = db.Column(db.Integer, primary_key=True)
    location_id = db.Column(db.Integer,db.ForeignKey('location.id'), nullable=False)
    location = db.relationship("LocationModel", back_populates="messages")
    content = db.Column(db.String)

    def __init__(self, message_id, content):
        self.message_id = message_id
        self.content = content

I would like to create an endpoint in the app that allows a user to provide location_name and content and it then creates a new location using the name and a new message using content and sets the foreign key location_id for location as being the id of the new location.

I tried to follow Inserting new records with one-to-many relationship in sqlalchemy

I created a class method

@classmethod
def add_both(cls, name, content):
    l = cls(name)
    m = MessageModel(content=content)
    l.messages.append(m)
    db.session.add(l)
    db.session.add(m)
    db.session.commit()

But I get an error because __init__ is missing the required location_id

Is there a better way to do this?

Charlie Morton
  • 737
  • 1
  • 7
  • 17

0 Answers0