F
F
freelion2022-01-30 19:02:13
Flask
freelion, 2022-01-30 19:02:13

How to make nested fields in marshmallow?

I have a very simple model and diagram:

class Exam(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    subject = db.Column(db.String(255))
    teacher = db.Column(db.String(255))
    room = db.Column(db.Integer)

    def __init__(self, subject, teacher, room):
        self.subject = subject
        self.teacher = teacher
        self.room = room

class ExamSchema(ma.Schema):
    class Meta:
        fields = ("id", "subject", "teacher", "room")


I get a response in JSON:
{
  "id": 1,
  "subject": "Math",
  "teacher": "John Doe",
  "room": 405
},
{
  "id": 2,
  "subject": "Geometry",
  "teacher": "John Doe",
  "room": 406
}


I would like to make a grouping by teacher, like this:
teacher: "John Doe",
exams: {[
 id, subject, room ...
]}


How to change the scheme to get such an object at the output?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
Gleb, 2022-01-31
@Hrafnir

Umm, don't you do this grouping in the query to the database? order_by(exam.teacher) ?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question