I’m a complete nab with python.
But now I need a simple storage containing MyObject-objects for some project.
Each object contains a few StringProperties nothing fancy.
Now I want to get from my list of MyObjects, 10 random objects and store them in some other array.
So I went searching and found random.sample and started implemending it.
def get10RandomMyObjects():
# waarders maken
dict = {}
myObjectsList = []
# Lijst vullen
myObjects = MyObject.all()
randomMyObjects = random.sample(myObjects, 10)
for o in randomMyObjects:
dict_myObject = { }
#some random property setting
myObjectsList.append(dict_myObject)
dict['myObjects'] = myObjectsList
return dict
This is the error I get back:
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/random.py", line 314, in sample
n = len(population)
TypeError: object of type 'Query' has no len()
So obviously something is wrong with the random.sample but my noobness can’t decypher what it is.
Anyone care to explain me why I can’t obtain those 10 random MyObjects I so desire?
random.sample()works on lists. Obviously,MyObject.all()does not return a list but aQueryobject. IfQueryis at least iterable then you can write:Otherwise, you have to create a list from
MyObject.all()manually.