1

I am trying to create a test for a Model from a nested dictionary schema:

from marshmallow import fields, Schema
from sqlalchemy.orm import relationship
from flask_sqlalchemy import SQLAlchemy

db = SQLAlchemy()

class PetSchema(Schema):
    id = fields.Number(attribute="id")
    name = fields.String(attribute="name")

class Pet(db.Model):
    __tablename__ = "pet"
    id = db.Column(db.Integer(), primary_key=True)
    name = db.Column(db.String(5))
    owners = relationship("Owner", back_populates="pet")

    def __repr__(self):
        return "<Pet %s>" % self.id

class OwnerSchema(Schema):
    id = fields.Number(attribute="id")
    theme_id = fields.Number(attribte="theme_id")
    pet_id = fields.Number(attribute="pet_id")
    name = fields.String(attribute="name")
    description = fields.String(attribute="description")
    pet = fields.Nested(
        PetSchema
    )

class Owner(db.Model):
    __tablename__ = "owner"
    id = db.Column(db.Integer(), primary_key=True)
    description = db.Column(db.String())
    name = db.Column(db.String(250))
    pet_id = db.Column(
        db.Integer(), db.ForeignKey("pet.id"), nullable=False
    )
    pet = relationship("Pet", back_populates="owners")

    def __repr__(self):
        return "<Owner %s>" % self.id

if __name__ == "__main__":
    schema = OwnerSchema()

    pet_nested = {
        "id": 2, 
        "name": "Katty",
    }

    result = schema.load(
        {
            "id": 12,
            "description": "This is a nice owner.",
            "name": "Owner name",
            "pet_id": 2,
            "pet": pet_nested,
        }
    )
    owner = Owner(**result)
    assert owner.id == 12

But for some reason I am getting this cryptic error which I am not understanding how to handle:

AttributeError: 'dict' object has no attribute '_sa_instance_state'

I saw this answer which suggests using ModelSchema instead of Schema. Should I use flask-marshmallow ModelSchema only? I also tried instead of using pet_nested in the dictionary Pet(**pet_nested) instead which gives me a new error. Without any nesting everything works. What am I doing wrong? Thanks in advance!

Blind0ne
  • 1,015
  • 12
  • 28
  • 1
    This thread might also be helpful? https://stackoverflow.com/questions/16151729/attributeerror-int-object-has-no-attribute-sa-instance-state?rq=1 Sadly I am currently having the same issue as you. – tzengia Jun 26 '22 at 05:32

0 Answers0