0

I am trying to invoke below mentioned query and not seeing the department_info field in the json response .If I use name "Department", the department details are returning.Is there any way to use different name for the nested query result? .Please see the query,model and marshmallow schema detail below

resp = db.session.query(Employee,Department).select_from(Employee).outerjoin(Department,Employee.department_id== Department.id).filter(Employee.id == emp_id).first()

data = EmployeeSchema.dump(resp)
return jsonify(data)



class Employee(db.model)
  id = db.column(db.Integer, primary_key=True)
  name = db.column(db.String(45))
  department_id = db.Column(db.Integer. db.ForeignKey(Department.id))

class Department(db.model)
  id = db.column(db.Integer, primary_key=True)
  name = db.column(db.String(45))
  
class DepartmentSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name')

class EmployeeSchema(ma.Schema):
    class Meta:
        fields = ('id', 'name', 'department_info')
    department_info = ma.Nested(DepartmentSchema, many=True)

1 Answer 1

2

You also need to have the relationship defined in your models (and it needs to be the same name as your nested Marshmallow object.

class Employee(db.model):
    id = db.column(db.Integer, primary_key=True)
    name = db.column(db.String(45))
    department_id = db.Column(db.Integer. db.ForeignKey(Department.id))
    department_info = db.relationship("Department", primaryjoin="Department.id==Employee.department_id")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.