0

Hi guys I am new to flask and SQLAlchemy. I have a '/users' route that should return all the users in my DB. Inside a user object I have an events Object that can hold many events. I have made the relationship but i am unsure of what code to add to properly serialize the events when I query for all my users.

code for my models:

class User(db.Model):
    id = db.Column(db.String, primary_key=True)
    username = db.Column(db.String, unique=True, nullable=False)
    email = db.Column(db.String, unique=True, nullable=False)
    password = db.Column(db.String, nullable=False)
    admin = db.Column(db.Boolean, default=False)
    events = db.relationship('Event', backref='hosted_by')


class Event(db.Model):
    id = db.Column(db.String, primary_key=True)
    name = db.Column(db.String, nullable=False)
    description = db.Column(db.String(100), nullable=False)
    address = db.Column(db.String, nullable=False)
    date = db.Column(db.String, nullable=False)
    time = db.Column(db.String, nullable=False)
    lat = db.Column(db.Float, default=0)
    lng = db.Column(db.Float, default=0)
    user_id = db.Column(db.String, db.ForeignKey('user.id'))

Route to create new event:

@app.route('/users/<id>/events', methods=['POST'])
def create_event(id):
    data = request.get_json()

    user = User.query.filter_by(id=id).first()

    new_event = Event(id=str(uuid.uuid4()),
                      name=data['name'], description=data['description'], address=data['address'], date=data['date'], time=data['time'], hosted_by=user)

    db.session.add(new_event)
    db.session.commit()

    return event_schema.jsonify(new_event)

Route to query all users:

@app.route('/users', methods=['GET'])
def get_all_users():
    all_users = User.query.filter().order_by('username')
    result = users_schema.dump(all_users)

    # some missing code here?

    return jsonify({'Users': result})

if I run hit the route above I receive this error:

TypeError: Object of type Event is not JSON serializable

any help would be amazing. thanks!

My marshmallow schemas:

class UserSchema(ma.Schema):
    class Meta:
        fields = ('id', 'username', 'email', 'password', 'admin', 'events')

class EventSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'description', 'address',
                  'date', 'time', 'lat', 'lng', 'user_id')

user_schema = UserSchema()
users_schema = UserSchema(many=True)

event_schema = EventSchema()
events_schema = EventSchema(many=True)
Ben Shekhtman
  • 385
  • 5
  • 15
  • I'm guessing your `users_schema` is a marshmallow schema? Since you haven't included the definition of that schema, it is hard to say exactly - but look at https://stackoverflow.com/questions/37798116/sqlalchemy-relationship-and-marshmallow - you should probably define `events` as `fields.Nested(EventSchema, many=True)` – MatsLindh Oct 18 '21 at 21:37
  • hey! Sorry yes i am. I edited the post to incude the ma schemas – Ben Shekhtman Oct 18 '21 at 22:42
  • I think you're going to have to add the field explicitly to `UserSchema`: `events = fields.Nested(EventSchema, many=True)`, so that you tell marshmallow how to serialize the items contained under `events`. – MatsLindh Oct 19 '21 at 08:00

0 Answers0