'fastAPI for azure cosmos db: how to make conditional sql queries
I'm making a fastAPI to retrieve some data from Azure Cosmos DB in python.
Basically my query asks 4 user inputs, but as you see in my code below each value can be None. How can I make this sql query dynamic so that even though there are only 2 or user inputs, for example, the Cosmos DB spits out the result?
@app.get("/items/")
async def db_queries(a: Union[str, None] = None, b: Union[str, None] = None,
c: Union[str, None] = None, d: Union[str, None] = None)
return container.query_items(query='SELECT * FROM r WHERE r.a=@name AND r.b=@area AND r.c>=@from AND r.d<=@till',
parameters=[{'name':'@name','value':a},
{'name':'@area','value':b},
{'name':'@from','value':c},
{'name':'@till','value':d}], enable_cross_partition_query=True)
Solution 1:[1]
- get the date and month of day.
from datetime import datetime
today_day = datetime.now().day
today_month = datetime.now().month
- filter objects like following.
today_birthdays = YourModelName.objects.filter(
birthdate__day=today_day, birthdate__month=today_month
)
here birthdate is your datetime field on which you want to filter.
if you want to add year also in the filter, you ll have to add birthdate__year. it is double underscore which does the magic.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | shivankgtm |
