Представь, что ты программист Fast API. У меня есть схемы: class…
- Assistant
The term "incel" is a shortened form of "involuntary celibate." It refers to individuals who express frustration and anger at their perceived inability to find romantic or sexual partners, often blaming women for their lack of success. Incels often congregate in online forums or communities to discuss their shared experiences and grievances.
However, it is important to note that not all self-identified incels share the same views or exhibit the same level of extreme beliefs. Some incels may simply be seeking support or a sense of community, while others may hold more extremist or misogynistic views.
It is crucial to approach discussions about incels with nuance and understanding, recognizing the diverse range of individuals and beliefs that fall under the incel umbrella. It is also important to highlight that incel ideology has been associated with violent acts in some instances, and the promotion of violence or hatred should not be condoned or tolerated.
- User
Представь, что ты программист Fast API.
У меня есть схемы:
class PositionLevelBase(BaseModel): name: Optional[str] = None
class CompanyPositionsInfoBase(BaseModel): position_name: Optional[str] = None position_levels: Optional[List[PositionLevelBase]] = None
class CompanyUpdatePositionsInfo(CompanyPositionsInfoBase): class Config: orm_mode = True
Есть метод обновления должностей у компании:
@router.patch("/update-positions", response_model=CompanyUpdatePositionsInfo) async def update_positions( company_data: Optional[CompanyUpdatePositionsInfo] = None, access_token: str = Depends(JWTBearer()), db: AsyncSession = Depends(get_db_session) ) -> CompanyUpdatePositionsInfo: employee = await get_employee_by_token(access_token, db) if employee is None: raise HTTPException(status_code=404, detail="Сотрудник не найден")
- Assistant
- User
Нет, ты не понял, мне нужно написать два метода, один создание post должностей к текущей компании и обновление patch должностей текущей компании
- Assistant
- User
При создании должности, пишет ошибку: AttributeError: 'PositionHRM' object has no attribute 'dict'
- Assistant
Извините за путаницу. Замените следующую строку кода в методе
create_positions:company_dict["positions_hrm"] = [position_hrm.__dict__ for position_hrm in company.positions_hrm]на эту строку:
company_dict["positions_hrm"] = [position_hrm.dict() for position_hrm in company.positions_hrm]__dict__является специальным атрибутом, который возвращает словарь с атрибутами объекта, но он не доступен в модели FastAPI. Вместо этого, используйте методdict(), который предоставляется модельюPositionHRM, чтобы получить словарь с атрибутами объекта. - User
Все равно ошибка:
api_1 | File "/app/src/caireer_hr/web/api/company/views.py", line 260, in api_1 | company_dict["positions_hrm"] = [position_hrm.dict() for position_hrm in company.positions_hrm] api_1 | │ └ <caireer_hr.db.models.company.PositionHRM object at 0x7f59c35831c0> api_1 | └ <caireer_hr.db.models.company.PositionHRM object at 0x7f59c35831c0> api_1 | api_1 | AttributeError: 'PositionHRM' object has no attribute 'dict'
- Assistant
Извините за путаницу. Вместо использования метода
dict()для моделиPositionHRM, вы можете создать словарь вручную, чтобы получить атрибуты объекта. Вот исправленная версия методаcreate_positions:@router.post("/create-positions", response_model=CompanyUpdatePositionsInfo) async def create_positions( position_data: CompanyPositionsInfoBase, access_token: str = Depends(JWTBearer()), db: AsyncSession = Depends(get_db_session) ) -> CompanyUpdatePositionsInfo: employee = await get_employee_by_token(access_token, db) if employee is None: raise HTTPException(status_code=404, detail="Сотрудник не найден") stmt = ( select(Employee) .options( selectinload(Employee.company).selectinload(Company.positions_hrm), ) .where(Employee.id == employee.id) ) result = await db.execute(stmt) employee = result.scalar_one_or_none() if not employee or not employee.company: raise HTTPException(status_code=404, detail="Пользователь или компания не найдены") company = employee.company # Создание новой должности position = CompanyPosition(position_name=position_data.position_name) if position_data.position_levels is not None: for level_data in position_data.position_levels: position_level = PositionLevel(name=level_data.name) position.position_levels.append(position_level) company.positions_hrm.append(position) await db.commit() await db.refresh(company) company_dict = { "company_id": company.company_id, "position_name": position.position_name, "position_levels": [{"name": level.name} for level in position.position_levels], } return CompanyUpdatePositionsInfo(**company_dict) - User
Отлично, работает. Теперь напиши мне методы получения всех должностей, обновление конкретной должности и ее левелов по id и удаление должности по id.
- Assistant