litestar-org / advanced-alchemy

A carefully crafted, thoroughly tested, optimized companion library for SQLAlchemy
http://docs.advanced-alchemy.litestar.dev/
MIT License
243 stars 30 forks source link

Bug: or Feature? SQLAlchemyDTO ignores include/exclude config when generating field definitions #236

Open bookin opened 3 months ago

bookin commented 3 months ago

Description

I've encountered an issue while using SQLAlchemyDTO with a SQLAlchemy model (without using Litestar's mixins). The DTO configuration to include only specific fields is being ignored, leading to unexpected behavior in my case.

class ReturnModelDTO(SQLAlchemyDTO[SomeModel]):
    config = SQLAlchemyDTOConfig(include={"id", "name"}, partial=False)

@get('/test', return_dto=ReturnModelDTO)
async def get_data(self) -> list[SomeModel]:
    ...

class SomeModel(DeclarativeBase, AsyncAttrs):
    __tablename__ = 'some_table'
    id = mapped_column(Integer, primary_key=True, autoincrement=True)
    name = mapped_column(String, nullable=False)
    topic_id = mapped_column(UUID, ForeignKey("topic.id"), nullable=False)
    topic: Mapped["Topic"] = relationship("Topic", lazy="joined")

I receive the following error:

raise NotImplementedError()

This error occurs in the following line:

return FieldDefinition.from_annotation(Optional[elem.type.python_type])

The error seems to be related to a field in the Topic model. However, I'm not sure why SQLAlchemyDTO is attempting to get field definitions for the relation when I've explicitly set the include config to only include "id" and "name".

Upon investigation, it appears that the generate_field_definitions(...) method in SQLAlchemyDTO doesn't utilize the include / exclude config keys. Instead, it generates definitions for all fields found in the model.

Is this behavior intended, or is it a bug?

Thank you for your time and assistance.

URL to code causing the issue

No response

MCVE

No response

Steps to reproduce

No response

Screenshots

No response

Logs

No response

Package Version

2.9.1

Platform