class ParentEntity(Base):
__tablename__ = "parent_entity"
id = Column(Integer, primary_key=True)
status = Column(String)
config_id = Column(Integer, ForeignKey("config_table.id"), nullable=False)
updated_at = Column(DateTime)
is_active = Column(Boolean, default=True)
config = relationship("ConfigTable", back_populates="parent_entities", lazy="selectin")
child_entities = relationship(
"ChildEntity",
back_populates="parent_entity",
primaryjoin="and_(ParentEntity.id == ChildEntity.parent_id, ChildEntity.is_active == true())",
lazy="selectin"
)
class ChildEntity(Base):
__tablename__ = "child_entity"
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey("parent_entity.id"))
client_id = Column(Integer) #
name = Column(String(255))
is_active = Column(Boolean, default=True)
parent_entity = relationship("ParentEntity", back_populates="child_entities", lazy="select")
class ConfigTable(Base):
__tablename__ = "config_table"
id = Column(Integer, primary_key=True)
entity_type = Column(String(255))
parent_entities = relationship("ParentEntity", back_populates="config", lazy="selectin")
< /code>
Метод репозитория родителей. < /p>
async def get_all_parent_entities_with_children(
db: AsyncSession,
entity_type: str,
start_date: Optional[datetime] = None,
end_date: Optional[datetime] = None,
status_filter: Optional[str] = None,
skip: int = 0,
limit: int = 10
) -> Tuple[List[Optional[ParentEntity]], int]:
"""Retrieve all ParentEntities with ChildEntities and Config details."""
try:
# Dynamic conditions
conditions = [ParentEntity.is_active == True]
if status_filter:
conditions.append(ParentEntity.status == status_filter)
if start_date:
conditions.append(ParentEntity.updated_at >= start_date)
if end_date:
conditions.append(ParentEntity.updated_at
Я использую ниже логику в моем методе службы вызов выше метода репозитория < /p>
# Filter child_entities by client_id if provided
filtered_children = (
list(filter(
lambda c: c.client_id == given_client_id,
parent_entity.child_entities
))
if given_client_id is not None
else parent_entity.child_entities
)
< /code>
В методе хранилища, если я прохожу предел как 100 и пропущу 0, я получу 100 объектов родительского класса из метода репозитория. Если dead_client_id передается методу службы с использованием этой логики фильтра, которую я вставил, он также передает объекты родительских объектов с нулевым списком детей []. Но я хочу вернуть список 100 родительских объектов из обслуживания тех родителей, у которых есть не по крайней мере 1 дочерний элемент [] с соответствующим детьми. В репозитории слой, но снова и снова терпит неудачу. Пожалуйста, помогите мне здесь. Я не могу понять, как сделать это в Python, используя Fastapi и Sqlalchemy.
Подробнее здесь: https://stackoverflow.com/questions/797 ... thon-fasta