[英]Python Combining a FOR Loop and an IF statement
I have some issues with this small piece of code: 我对这一小段代码有一些问题:
for key in UserInput.objects.all():
if UserInput.category_id == 2:
data = {}
data['label'] = key.input_date
data['value'] = key.input_value
dataSource['data'].append(data)
I just don't seem to get it working. 我似乎没有让它工作。 The only thing I want to do is to retrieve all rows from the UserInput table which have a category_id of 2 and then execute the four data lines for each row to use in my bar chart. 我唯一想做的就是从UserInput表中检索category_id为2的所有行,然后为我的条形图中使用的每一行执行四行数据。
I get a variety of errors. 我遇到了各种各样的错误。 I get an Object of type date is not JSON serializable on data['label'] = key.input_date. 我在数据['label'] = key.input_date上得到一个类型为date的对象不是JSON可序列化的。 If I replace input_date with another (string) value, my bar chart seems to work, but it shows an empty bar chart. 如果我将input_date替换为另一个(字符串)值,我的条形图似乎可以工作,但它显示一个空条形图。 I tried to serialize my input_date, but I get even more errors when I try to do that. 我试图序列化我的input_date,但是当我尝试这样做时,我会遇到更多错误。
json_data = serializers.serialize("xml", UserInput.objects.all())
and 和
fields = ['input_date']
qs = UserInput.objects.all()
json_input_data = serializers.serialize('json', qs, fields=fields)
My Python knowledge doesn't reach far enough to solve this on my own. 我的Python知识远远不足以自行解决这个问题。
I would prefer to sort the data to month-year instead of day-month-year, but I would understand if this is beyond the scope of my question 我更愿意将数据分类为月 - 而不是日 - 月 - 年,但我会理解这是否超出了我的问题的范围
EDIT: As many pointed it out in the comments, I do indeed use Django. 编辑:正如许多人在评论中指出的那样,我确实使用了Django。 I didn't mention it before because I thought it wouldn't be relevant. 我之前没有提到它,因为我认为它不相关。
Seems like you are using Django, so you should use the tools provided by Django . 好像你正在使用Django,所以你应该使用Django提供的工具 。
objects_with_category_id_2 = UserInput.objects.filter(category_id=2)
for obj in objects_with_category_id_2:
data = {'label': obj.input_date,
'value': obj.input_value}
dataSource['data'].append(data)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.