我正在尝试从这个 json 中打印所有汽车:
{
"stuff": [
{
"car" : 1,
"color" : "blue"
},
{
"bcarus" : 2,
"color" : "red"
}
],
}
Run Code Online (Sandbox Code Playgroud)
In my Serializer I access the data like this....
stuff = self.context.get("request").data.stuff
But when I do the following...
for item in stuff:
print(item)
Run Code Online (Sandbox Code Playgroud)
I get he error:
'builtin_function_or_method' object is not iterable
Why do I get this error?
How can I access stuff in a for loop?
When I do print(self.context.get("request").data.stuff) I get <built-in method items of dict object at 0x105225050> which I assumed print the stuff instead.
stuff ends up a method of function so you would need to call it:
for item in stuff():
print(item)
Run Code Online (Sandbox Code Playgroud)
Which based on your comment is the dict.items.
So you can unpack:
for k,v in stuff():
print(k,v)
Run Code Online (Sandbox Code Playgroud)
Or just call when you assign:
stuff = self.context.get("request").data.stuff()
for k,v in stuff:
print(k,v)
Run Code Online (Sandbox Code Playgroud)