![](/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.