1

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.

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?

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

4

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)

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

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]
于 2013-06-19T14:39:08.047 回答