I'm using Postgresql, FastApi, Sqlalchemy, Pydantic I have a model called "Company" one column of the model is postgresql "JSONField" In this model, I plan to keep company addresses as a list.
I managed to add an address to field, but when I want to update or delete any of these addresses, I don't know what to do.
My Pydantic schema
from pydantic import BaseModel, Json
from typing import Optional,List,Dict
class addresses(BaseModel):
id:int
name:str
class Config:
orm_mode=True
class customers_companies(BaseModel):
name:str
#addresses: Json[List[addresses]]
addresses: List[addresses]
class Config:
orm_mode=True
Post router
@customers_router.post('/companies')
def create_company(request:schemas.customers_companies, db: Session = Depends(get_db)):
new_company = models.Customers_Companies(name=request.name,addresses= jsonable_encoder(request.addresses))
db.add(new_company)
db.commit()
db.refresh(new_company)
return new_company
Get router by ID
@customers_router.get('/companies/{id}', response_model=schemas.customers_companies)
def get_company(id, db: Session = Depends(get_db)):
company = db.query(models.Customers_Companies).filter(models.Customers_Companies.id==id).first()
return company
Result of > Get router by ID
for example I want to update only the address with id=1.
{
"name": "string",
"addresses": [
{
"id": 1,
"title": "Address 1"
},
{
"id": 2,
"title": "Address 2"
}
]
}