2017-01-25 12 views
0

플라스크, flask-sqlalchemy 및 flask-marshmallow를 사용하여 작은 REST API를 빌드하고 있습니다. 일부 요청에 대한 내 sqlalchemy 개체로 구성된 json 직렬화 된 응답을 반환하고 싶습니다. 그러나 다차원 (many-to-many) 관계/보조 테이블을 사용할 때 열심히로드 된 sqlalchemy 개체로 작업 할 직렬화를 얻을 수 없습니다. 여기 Flask Marshmallow/SqlAlchemy : 다 대 다 관계 직렬화

은 간단한 예입니다, 더 많거나 적은 복사/플라스크-마시 멜로 문서에서 붙여 넣기 : 나는 열심히 책을로드뿐만 아니라 저자의 객체를 얻을 수 위의 코드를 기반으로
from flask import Flask 
from flask_sqlalchemy import SQLAlchemy 
from flask_marshmallow import Marshmallow 
from sqlalchemy.orm import joinedload 

app = Flask(__name__) 
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite://' 

# Order matters: Initialize SQLAlchemy before Marshmallow 
db = SQLAlchemy(app) 
ma = Marshmallow(app) 

secondary_foo = db.Table('secondary_foo', 
          db.Column('author_id', db.Integer, db.ForeignKey('author.id')), 
          db.Column('book_id', db.Integer, db.ForeignKey('book.id'))) 

class Author(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    name = db.Column(db.String(255)) 

class Book(db.Model): 
    id = db.Column(db.Integer, primary_key=True) 
    title = db.Column(db.String(255)) 
    authors = db.relationship('Author', secondary="secondary_foo", backref='books', lazy="joined") 

class AuthorSchema(ma.ModelSchema): 
    class Meta: 
     model = Author 

class BookSchema(ma.ModelSchema): 
    #authors = ma.Nested(AuthorSchema) <-- Doesn't work, authors will be serialized to empty json object, instead of list of ids 
    class Meta: 
     model = Book 


db.drop_all() 
db.create_all() 
author_schema = AuthorSchema() 
book_schema = BookSchema() 
author = Author(name='Chuck Paluhniuk') 
book = Book(title='Fight Club') 
book.authors.append(author) 
db.session.add(author) 
db.session.add(book) 
db.session.commit() 

s = BookSchema(many=True) 

.

print(s.dump(Book.query.filter(1==1).options(joinedload('authors')).all()).data) 
//--> [{'authors': [{'name':'Chuck Paluhniuk', 'id':'1'}], 'title': 'Fight Club', 'id': 1}] 

도대체 내가 :-) 있음을 어떻게해야합니까 :

print(Book.query.filter(1==1).options(joinedload('authors')).all()[0].authors) 
//--> [<__main__.Author object at 0x1043a0dd8>] 

print(s.dump(Book.query.filter(1==1).options(joinedload('authors')).all()).data) 
//--> [{'authors': [1], 'title': 'Fight Club', 'id': 1}] 

이 내가 원하는 결과가 : 깊은 객체를 직렬화 때 ID 목록에 직렬화? 당신이 있었다 (그러나 주석)처럼 BookSchema에서

답변

1

, 당신은 Nestedauthors 필드를 추가 할 수 있습니다하지만 당신은 그것이 many keyword argument를 사용하여 목록이 될 것이라는 점을 지정할 수 있습니다.

class BookSchema(ma.ModelSchema): 

    # A list of author objects 
    authors = ma.Nested(AuthorSchema, many=True) 

    class Meta: 
     model = Book 
+0

감사합니다. 플라스크 -marshmallow, flask-sqlalchemy, sqlalchemy 및 marsmallow docs를 끝내고 몇 시간을 보냈 음에 틀림 없습니다. – MSurrow