如何从ValuesQuerySet中获取值

时间:2022-04-30 09:58:35

I'm trying to extract some data from my database in my Django app with the following line of code. Job is the name of my model and jobIDs[i] represents the id of the record being operated on.

我正在尝试使用以下代码行从我的Django应用程序中的数据库中提取一些数据。 Job是我的模型的名称,jobIDs [i]表示正在操作的记录的id。

timeToRun = Job.objects.filter(id=jobIDs[i]).values()['whenToRun'].split(' ')[0]

When I get to ['whenToRun'] I get a TypeError(). Am I misunderstanding how to access values in this kind of dict?

当我到['whenToRun']时,我得到一个TypeError()。我是否误解了如何在这种字典中访问价值观?

EDIT: To clarify, .values() return a ValuesQuerySet

编辑:澄清一下,.values()返回一个ValuesQuerySet

1 个解决方案

#1


1  

Probably this is what you are looking for:

可能这就是你要找的东西:

timeToRun = Job.objects.filter(id=jobIDs[i]).values()[0]['whenToRun'].split(' ')[0]

From the documentation values() is a ValueQuerySet (a list of queryset objects)

从文档值()是一个ValueQuerySet(查询集对象列表)

Now, if Job.objects.filter(id=jobIDs[i]) returns empty queryset, it would throw an error, so I would do:

现在,如果Job.objects.filter(id = jobIDs [i])返回空的queryset,它会抛出一个错误,所以我会这样做:

if Job.objects.filter(id=jobIDs[i]).exists(): #a quick lookup
    timeToRun = Job.objects.filter(id=jobIDs[i]).values()[0]['whenToRun'].split(' ')[0]

One more level of optimization:

另一个优化级别:

if Job.objects.filter(id=jobIDs[i]).exists(): #a quick lookup
    timeToRun = list(Job.objects.filter(id=jobIDs[i]).values_list('whenToRun', flat=True))[0].split(' ')[0]

#1


1  

Probably this is what you are looking for:

可能这就是你要找的东西:

timeToRun = Job.objects.filter(id=jobIDs[i]).values()[0]['whenToRun'].split(' ')[0]

From the documentation values() is a ValueQuerySet (a list of queryset objects)

从文档值()是一个ValueQuerySet(查询集对象列表)

Now, if Job.objects.filter(id=jobIDs[i]) returns empty queryset, it would throw an error, so I would do:

现在,如果Job.objects.filter(id = jobIDs [i])返回空的queryset,它会抛出一个错误,所以我会这样做:

if Job.objects.filter(id=jobIDs[i]).exists(): #a quick lookup
    timeToRun = Job.objects.filter(id=jobIDs[i]).values()[0]['whenToRun'].split(' ')[0]

One more level of optimization:

另一个优化级别:

if Job.objects.filter(id=jobIDs[i]).exists(): #a quick lookup
    timeToRun = list(Job.objects.filter(id=jobIDs[i]).values_list('whenToRun', flat=True))[0].split(' ')[0]