title: Loading One to Many associated attribute with SQLalchemy and Marshmallow
body: <p>I'm building a flask api and I am trying to learn how to load a parent model's attribute from a 1-n relationship.</p>
  
  <p>First I load all Inventory items. This works great. My goal is to load each inventory items', parent model (Material) name attribute.</p>
  
  <p>Just to clear things up a Material has many Inventory items. An inventory item belongs to a material. And I have a collection of all inventory items. </p>
  
  <p>My goal is something like this:</p>
  
  <pre><code>{'id': 1, 'location': None, 'material_name': {'name': 'load name'}
  </code></pre>
  
  <p>But I am never loading the name, it returns blank:</p>
  
  <pre><code>{'id': 1, 'location': None, 'material_name': {'name': ''}
  </code></pre>
  
  <p>I'm using Marshmallow to create a flask-api and return nice JSON.</p>
  
  <p>here is my model.py</p>
  
  <pre><code>from app import db
  from marshmallow import Schema, fields
  
  class Material(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      name = db.Column(db.String(64), index=True, unique=False)
      items = db.relationship('Inventory', backref='material', lazy='dynamic')
  
  class Inventory(db.Model):
      id = db.Column(db.Integer, primary_key=True)
      location = db.Column(db.Integer, primary_key=False)
      material_id = db.Column(db.Integer, db.ForeignKey('material.id'))
      def __init__(self, material_name):
          self.material_name = material_name
  
  ##### SCHEMAS (marshmallow) #####
  # http://marshmallow.readthedocs.org/en/latest/examples.html
  
  class MaterialSchema(Schema):
      id = fields.Int(dump_only=True)
      name = fields.Str()
  
  class InventorySchema(Schema):
      id = fields.Int(dump_only=True)
      location = fields.Int(dump_only=True)
      material_name = fields.Nested(MaterialSchema, only=["name"])
  </code></pre>
  
  <p>and my query:</p>
  
  <pre><code>inventory_schema = InventorySchema(many=True)
  @api.route('/api/inventory', methods=['GET'])
  @cross_origin()
  def inventoryindex():
      d=request.args['q']
      if len(d) &gt;= 1:
          search_term = "%{0}%".format(d)
          count = Inventory.query.filter(Inventory.location.like(search_term)).count
          items = Inventory.query.filter(Inventory.location.like(search_term)).limit(10)
      else:
          count = Inventory.query.count()
          items = Inventory.query.limit(10)
      result = inventory_schema.dump(items)
      print(result)
      dictionary = {}
      for obj in result[0]:
          dictionary[obj['id']] = obj
      return jsonify({'dict':dictionary})
  </code></pre>
  
  <p>It returns everything I expect, except the material name is empty. How can I load the material id, from the inventory query above?</p>