Search code examples
pythonpython-3.xlistsqlalchemyfastapi

Python 3.11 , converting serialzier to data model object getting error object has no attribute '_sa_instance_state


I am new python and I am trying to convert serialize object to data model and my flow is Json request to serialize and from serialize to model-object in python to persist the object.

Json request :

{
    "id": "string",
    "href": "string",
    "category": "string",
    "description": "string",
    "administrativeState": "string",
    "attachment": [
        {
            "id": "string",           
            "attachmentType": "string"    
        }
    ],
    "operationalState": "string",
    "resourceStatus": "string"
}

and my serilizer class

class ResourceReq(BaseModel):
    id : Optional[int]
    href : str
    category: str
    description: str    
    administrativeState: str
    attachment: List[Attachment]
    operationalState : str
    resourceStatus : str
   
   
 class Attachment(BaseModel):
        id:str
        attachmentType : str

and My model class

class Resource(Base):
    __tablename__ = 'resource'
    
    id = Column(Integer, primary_key=True, index=True, autoincrement=True)
    category = Column(String(255), nullable=True)
    description = Column(String(255), nullable=True)
    href = Column(String(255), nullable=True)
    operationalState = Column(String(255), nullable=True) 
    resourceStatus = = Column(String(255), nullable=True)
    attachment = relationship("AttachmentRefOrValue", back_populates="resource" )
    
class AttachmentRefOrValue(Base):
    __tablename__ = 'attachment_ref_or_value'

    attachmentType = Column(String(255), nullable=True)
    id = Column(String(255), nullable=True)
    resource_id = Column(Integer(), ForeignKey("resource.id"))
    resource = relationship("Resource", back_populates="attachment")

here i am converting to serializer to model

def creatResource(resourcesInventory : ResourceReq) -> resource_models.Resource :
    newResourcesInventory  = resource_inventory_models.Resource(**resourcesInventory.__dict__)

   
    return newResourcesInventory

when i call this this method i am getting below error ,

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


Solution

  • resourcesInventory.attachment is a list of Pydantic models, which can't be converted directly to a SQLAlchemy object. You need to do something like

    def creatResource(resourcesInventory: ResourceReq) -> resource_models.Resource:
        attachment = [
            resource_inventory_models.AttachmentRefOrValue(**a.model_dump())
            for a in resourcesInventory.attachment
        ]
        newResourcesInventory  = resource_inventory_models.Resource(
            **resourcesInventory.model_dump(exclude=["attachment"]),
            attachment=attachment,
        )
        return newResourcesInventory