I want select column in sqlalchemy and return result with fastapi
I run this query :
stmt = select(OrderAllocate)
return session.scalars(stmt).all()
Worked and return list object
Now i want return list object just two field and i use this command:
stmt = select(OrderAllocate.quantity, OrderAllocate.stock_id)
return session.execute(stmt).all()
return list tuple but i want list object becuse touple problem return with fastapi
Related
I want to fetch data of multiple ids which is provided from the User Interface and these ids are stored in a list. So how can I retrieve the data of these ids using Django ORM?
When I try the following approach It returned nothing
def selectassess(request):
if request.method=='POST':
assess=request.POST.getlist("assess")
quesno=request.POST.getlist("quesno")
subid=request.POST.getlist("subid")
print(quesno,subid)
print(assess)
max_id = Sub_Topics.objects.all().aggregate(max_id=Max("id"))['max_id']
print(max_id)
pk = random.sample(range(1, max_id),3)
subss=Sub_Topics.objects.raw("Select * from Sub_Topics where id=%s",(str(pk),))
context4={
'subss':subss,
}
print(pk)
return render(request,"assessment.html",context)
By applying the below-mentioned approach I can get only one id-data which is specified by typing the index value. But I want to get the data of all ids which are stored in the list so how can I get my required output by using Django ORM
def selectassess(request):
if request.method=='POST':
assess=request.POST.getlist("assess")
quesno=request.POST.getlist("quesno")
subid=request.POST.getlist("subid")
print(quesno,subid)
print("youuuuu")
print(assess)
max_id = Sub_Topics.objects.all().aggregate(max_id=Max("id"))['max_id']
print(max_id)
pk = random.sample(range(1, max_id),3)
sub = Sub_Topics.objects.filter(pk=pk[0]).values('id','subtopic')
context4={
'sub':sub,
}
print(pk)
return render(request,"assessment.html",context4)
You can use filter(pk__in=pk).
Try:
list_of_ids = random.sample(range(1, max_id),3)
sub = Sub_Topics.objects.filter(id__in=list_of_ids).values('id','subtopic')
How would I go about using the django.db.models Q module to query multiple lines of input from a list of data using a <textarea> html input field? I can query single objects just fine using a normal html <input> field. I've tried using the same code as my input field, except when requesting the input data, I attempt to split the lines like so:
def search_list(request):
template = 'search_result.html'
query = request.GET.get('q').split('\n')
for each in query:
if each:
results = Product.objects.filter(Q(name__icontains=each))
This did not work of course. My code to query one line of data (that works) is like this:
def search(request):
template = 'search_result.html'
query = request.GET.get('q')
if query:
results = Product.objects.filter(Q(name__icontains=query))
I basically just want to search my database for a list of data users input into a list, and return all of those results with one query. Your help would be much appreciated. Thanks.
Based on your comments, you want to implement OR-logic for the given q string.
We can create such Q object by reduce-ing a list of Q objects that each specify a Q(name__icontains=...) constraint. We reduce this with a "logical or" (a pipe in Python |), like:
from django.db.models import Q
from functools import reduce
from operator import or_
def search_list(request):
template = 'search_result.html'
results = Product.objects.all()
error = None
query = request.GET.get('q')
if query:
query = query.split('\n')
else:
error = 'No query specified'
if query:
results = results.filter(
reduce(or_, (Q(name__icontains=itm.strip()) for itm in query))
)
elif not error:
error = 'Empty query'
some_context = {
'results' : results,
'error': error
}
return render(request, 'app/some_template.html', some_context)
Here we thus first check if q exists and is not the empty string. If that is the case, the error is 'No query specified'. In case there is a query, we split that query, next we check if there is at least one element in the query. If not, our error is 'Empty query' (note that this can not happen with an ordinary .split('\n'), but perhaps you postprocess the list, and for example remove the empty elements).
In case there are elements in query, we perform the reduce(..) function, and thus filter the Products.
Finally here we return a render(..)ed response with some_template.html, and a context that here contains the error, and the result.
I have this view
def view_involved_people(request):
schedule = request.POST['schedule']
query = Schedule.objects.get(pk=schedule)
serialized = serializers.serialize('json', query)
data = {'people': serialized}
return JsonResponse(data)
It displays that the object is not iterable. I think it is because I am only getting one instance of the object. However, how can I prevent this error and get this data from the view?
I have tried using .filter() but when I call data.attribute_name, it does not display the value
You have to use filter in you case:
def view_involved_people(request):
schedule = request.POST['schedule']
query = Schedule.objects.filter(pk=schedule)
serialized = serializers.serialize('json', query)
data = {'people': serialized}
return JsonResponse(data)
I have a simple query which is
select distinct roleid,firstname,lastname where role_id='210';
I am using the same query for fetching the different lists such as projectnames ,projectmanagers name,developers...etc..based on the roleid that I am passing.
My problem is I need to run the above query in a single shot by passing all the roleid and retrieve them in a single hit and assign those list to different list such as managers list ,developers list ,testers list ..etc and send it to the UI putting them in a linked hasmap.
Example
LinkedHashMap<String, List<SelectItem>> results = new LinkedHashMap<String, List<SelectItem>>();
List<SelectItem> getProjectManager = getProjectManager(xxx);
List<SelectItem> getResourceOwnerSE = getResourceOwner(yyy);
List<SelectItem> getReqLeadPri = getReqLeadPri(zzz);
results.put("getProjectManager", getProjectManager);
results.put("getResourceOwner", getResourceOwnerSE);
results.put("getReqLeadPri", getReqLeadPri);
return results;
All the above methods getProjectManager(xxx),getResourceOwner(yyy),getReqLeadPri(zzz) runs with same query as mentioned above but passing different roleid xxx,yyy,zzz.
I don't know how to fetch a different list from a single query passing different parameters and assign to the list and return the results.
I am trying to achieve this because the UI is very slow when I try to get the lists individually from UI <-> DB each time when calling the same query passing different parameters each time for fetching different list.
Hence, I am trying to get the results in a single shot.
If you want to fir only one sql statement you can use ResultSetExtractor
public class SelectItemResultSetExtractor implements ResultSetExtractor<LinkedHashMap<String, List<SelectItem>>>{
public LinkedHashMap<String, List<SelectItem>> extractData(ResultSet rs) throws SQLException,
DataAccessException {
LinkedHashMap<String, List<SelectItem>> result = new ...
//put the 3 categories with empty arraylists
while(rs.next()){
SelectItem item= new SelectItem();
item.setRoleid(rs.getInt(1))
item.setFirstName(rs.getInt(2));
item.setLastName(rs.getString(3));
//if item.getRoleid() is ProjManager
// then put in the list of the ProjManager
result.get("ProjManager").add(item);
//if item.getRoleid() is ResourceOwnerSE
// then put in the list of the ResourceOwnerSE
...
}
return result;
}
}
I am try to perform a RAW SQL query in django. I am having some trouble getting the fetchall result to output a list of the distinct items in a column.
So I am hoping to get a list of all the items in a column.
class TableObject (object):
def __init__ (self, Kingdom):
SQL_str_Table = "SELECT DISTINCT column_title FROM sql_table"
cursor.execute(SQL_str_Table, [])
listOfReturns = cursor.fetchall()
for each in listOfReturns:
item = each
when I try a print out of "item" I get:
"bound method TableObject.write of mysite.forms.veiws.TableObject object at 0x03E5EE70"
So my question is how do I get the fetchall result into a list.
If you want to get a flat list of only column_title's then you can do this:
listOfReturns = cursor.fetchall()
listOfReturns_flat = [i for i in listOfReturns if i[0]] #remove empty results if any