![](/img/trans.png)
[英]Django rest framework viewset get_queryset() doesn't return correct queryset
[英]Django REST Framework - return a value from get_queryset?
我正在嘗試從get_queryset
返回一個value
。
def get_queryset(self):
if self.request.user.is_superuser:
return StockPriceModel.objects.order_by('ticker').distinct()
elif not self.request.user.is_authenticated:
print('in')
print(self.request.data)
last_price = StockPriceModel.objects.all().filter(
ticker=self.request.data['ticker']).order_by('-last_date_time')[0].last_price
print(last_price)
return last_price
最后的價格可以毫無問題地打印出來。
作為return
,我收到各種錯誤:
/api/stock-prices-upload/ 'float' 對象的 TypeError 不可迭代
如果我嘗試return
直到:
StockPriceModel.objects.all().filter(
ticker=self.request.data['ticker']).order_by('-last_date_time')
有用。
一旦我嘗試僅返回0
位置查詢集,就會出現錯誤。
我認為這是因為get_queryset
應該返回一個queryset
。 不確定如何只返回值。
編輯:
我現在試圖只獲取最新的行,即[0]
形成數據,但仍然出現相同的錯誤,即
StockPriceModel 對象不可迭代
# The current output if I don't add the [0] i.e. try to get the last row of data
[{"id":23,"last_price":"395.2","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":null,"last_date_time":"2022-10-20T15:58:26+04:00","created_at":"2022-10-20T23:20:37.499166+04:00"},{"id":1717,"last_price":"437.5","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":438.9,"last_date_time":"2022-11-07T15:53:41+04:00","created_at":"2022-11-07T14:26:40.763060+04:00"}]
預期響應:
[{"id":1717,"last_price":"437.5","name":null,"country":null,"sector":null,"industry":null,"ticker":"HINDALCO","high_price":438.9,"last_date_time":"2022-11-07T15:53:41+04:00","created_at":"2022-11-07T14:26:40.763060+04:00"}]
我試過使用last
、 get
等。只是行不通。
因為, get_queryset()
總是返回對象的查詢集或對象列表。
您不能從get_queryset
方法返回對象或字段。
last_price
值將被打印,但它是一個字段值,因此get_queryset
方法不會返回它。
添加[0]
時,它會從過濾的查詢集中獲取第一個對象。 到那時,它是對象的查詢集。
這有點 hacky,我相信一定有更好的方法來做到這一點。
我想獲得基於單行 (last_date_time) 或last_price
值的return
值。
我包裝了查詢:
# removed the .last_price
last_price = StockPriceModel.objects.all().filter(
ticker=self.request.data['ticker']).order_by('-last_date_time')[0]
last_price = [last_price] # made it into a list, i.e. iterable
return last_price
現在我可以得到最后一行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.