unique key constraint validation #4980
-
|
Hi Guys, I have some keys that need to be unique within the db table, but I can't figure out how to do so. so, what is the best practice to validate a unique key value? example case: # crud create
def create(self, db: Session, obj: CreateSchemaType) -> ModelType:
obj_data = jsonable_encoder(obj)
db_obj = self.model(**obj_data)
db.add(db_obj)
db.commit()
db.refresh(db_obj)
return db_obj
# model
class Company(Base):
__tablename__ = "companies"
id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True)
name = Column(String, nullable=False, index=True)
business_number = Column(String, nullable=False, index=True)
carrier_license_exp_date = Column(Date)
professional_manager = Column(JSON, nullable=False)
address = Column(JSON)
contact = Column(JSON)
email = Column(String)
fax_number = Column(String)
phone_number = Column(String)
# schema
class CompanyBase(BaseModel):
name: str
business_number: str
professional_manager: ProfessionalManager
carrier_license_exp_date: date | None
contact: Contact | None = None
address: Address | None = None
phone_number: str | None = None
fax_number: str | None = None
email: EmailStr | None = None
# endpoint
@router.post(
"/",
status_code=status.HTTP_201_CREATED,
response_model=schemas.Company,
response_model_exclude_none=True,
)
async def create_company(
company_obj: schemas.CompanyCreate,
db: Session = Depends(deps.get_db),
) -> Any:
company = crud.company.create(db=db, obj=company_obj)
return company |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
I think the right way is to go to your database and create a |
Beta Was this translation helpful? Give feedback.
I think the right way is to go to your database and create a
Unique Constraintin both columns, I think it's the simplest and best way to do so