filter_ann almost fixed

This commit is contained in:
DmitryGantimurov 2023-09-02 19:04:30 +03:00
parent f744cce713
commit 37d219c516
2 changed files with 35 additions and 27 deletions

View File

@ -3,7 +3,7 @@ from sqlalchemy.sql import text, literal_column
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from typing import Annotated from typing import Annotated
from fastapi import Depends from fastapi import Depends
from sqlalchemy import select from sqlalchemy import select, or_, and_
from . import auth_utils, orm_models, pydantic_schemas from . import auth_utils, orm_models, pydantic_schemas
import datetime import datetime
@ -49,35 +49,43 @@ async def add_poems_to_db(async_db: AsyncSession):
async def filter_ann(schema: pydantic_schemas.SortAnnouncements, db: AsyncSession): async def filter_ann(schema: pydantic_schemas.SortAnnouncements, db: AsyncSession):
"""Функция для последовательного применения различных фильтров (через схему SortAnnouncements)""" """Функция для последовательного применения различных фильтров (через схему SortAnnouncements)"""
# fields = schema.__dict__ # параметры передоваемой схемы SortAnnouncements (ключи и значения) fields = schema.__dict__ # параметры передоваемой схемы SortAnnouncements (ключи и значения)
# # проходим по названиям фильтров и их значениям # проходим по названиям фильтров и их значениям
# for name, filt_val in fields.items(): # выбираем все строки
# # создаем выражение sql запроса query = await db.execute(select(orm_models.Announcement))
# statement = text("SELECT * FROM announcements ") res = set(query.scalars().all())
# # выбираем все строки for name, filt_val in fields.items():
# query = await db.execute(statement) # res = await db.execute(statement)
# res = query.all() # если фильтр задан
# # если фильтр задан if filt_val is not None:
# if filt_val is not None: filter_query = await db.execute(select(orm_models.Announcement).where(literal_column(f"announcements.{name}") == filt_val))
# to_intersect_query = await db.execute(select(orm_models.Announcement).where(literal_column(f"announcements.{name}") == filt_val)) filtered = set(filter_query.scalars().all())
# to_intersect = to_intersect_query.all() res = res.intersection(filtered)
# res = res.intersect(to_intersect) # # отфильтровываем подходящие объявления
# res = await db.execute(
# select(orm_models.Announcement).where(
# ((schema.obsolete == None) | ((schema.obsolete != None) & (orm_models.Announcement.obsolete == schema.obsolete)))
# & ((schema.user_id == None) | ((schema.user_id != None) & (orm_models.Announcement.user_id == schema.user_id)))
# & ((schema.metro == None) | ((schema.metro != None) & (orm_models.Announcement.metro == schema.metro)))
# & ((schema.category == None) | ((schema.category != None) & (orm_models.Announcement.category == schema.category)))
# )
# )
# отфильтровываем подходящие объявления
res = await db.execute(select(orm_models.Announcement)
.where(schema.obsolete != None and orm_models.Announcement.obsolete == schema.obsolete
and schema.user_id != None and orm_models.Announcement.user_id == schema.user_id
and schema.metro != None and orm_models.Announcement.metro == schema.metro
and )
# .where(schema.user_id != None and orm_models.Announcement.user_id == schema.user_id) # .where(schema.user_id != None and orm_models.Announcement.user_id == schema.user_id)
# .where(schema.metro != None and orm_models.Announcement.metro == schema.metro) # .where(schema.metro != None and orm_models.Announcement.metro == schema.metro)
# .where(schema.category != None and orm_models.Announcement.category == schema.category) # .where(schema.category != None and orm_models.Announcement.category == schema.category)
)
# statement = text("SELECT * FROM announcements " # statement = text("SELECT * FROM announcements "
# "WHERE announcements.obsolete = :obsolete " # "WHERE announcements.obsolete = :obsolete "
# "AND announcements.user_id == :user_id " # "INTERSECT"
# "AND announcements.metro == :metro " # "SELECT * FROM announcements "
# "AND announcements.category == :category") # "WHERE announcements.user_id == :user_id "
# "INTERSECT"
# "SELECT * FROM announcements "
# "WHERE announcements.metro == :metro "
# "INTERSECT"
# "SELECT * FROM announcements "
# "WHERE announcements.category == :category")
# res = await db.execute(statement, # res = await db.execute(statement,
# {"obsolete": schema.obsolete, # {"obsolete": schema.obsolete,
@ -85,9 +93,9 @@ async def filter_ann(schema: pydantic_schemas.SortAnnouncements, db: AsyncSessio
# "metro": schema.metro, # "metro": schema.metro,
# "category": schema.category} # "category": schema.category}
# ) # )
# возвращаем все подходящие объявления # возвращаем все подходящие объявления
return res
return res.scalars().all()
async def check_obsolete(db: AsyncSession, current_date: datetime.date): async def check_obsolete(db: AsyncSession, current_date: datetime.date):

View File

@ -5,7 +5,7 @@ from sqlalchemy.ext.declarative import declarative_base
SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///./sql_app.db" SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///./sql_app.db"
# SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://postgres:D560c34V112Ak@localhost/porridger" # SQLALCHEMY_DATABASE_URL = "postgresql+asyncpg://postgres:D560c34V112Ak@localhost/porridger"
engine = create_async_engine(SQLALCHEMY_DATABASE_URL, echo=True) engine = create_async_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False) SessionLocal = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)