views:

76

answers:

5

I cannot run ['abc'].append( MyModel.objects.all() ) since it generates exception 'NoneType' object is not iterable if MyModel has no entry.

any workaround or something like ? : in c++

edit: my statement is actually

','.join([ str(e) for e in ['abc','def'].append( MyModel.objects.all() ) ])

it seems that the problem is caused by append() returning NoneType. I solved this by creating a variable to hold the list and then extend() it

A: 

Shouldn't it be += instead of append?

muckabout
Why should it? `list.append(x)` is a valid method http://docs.python.org/tutorial/datastructures.html
Felix Kling
+2  A: 

how about:

['abc'].append( MyModel.objects.all() or [])
Dmitry Shevchenko
OP's problem is caused by the in-place appending of a list. So you can't do it in a list comprehension.
Dingle
+1  A: 

Model.objects.all() is a QuerySet and that is iterable (see the source). Passing an iterator to list.extend works just fine: The contents of the iterator is unrolled nicely onto the end of the list.

NB: passing it to list.append puts the iterator object itself into the list, so most likely you want to extend().

Paul
+2  A: 

It might be best to be explicit rather than implicit (and avoid using the short circuit propoerties of or which can lead to errors:

my_objects = MyModel.objects.all()
if my_objects:
    [a,b,c].extend(my_objects)
blokeley
+1  A: 

None is returned from the append method, which takes place in place. In other words, your statement is equivalent to

[str(e) for e in None]

which naturally raises a NoneType exception. The solution is have a separate statement for the append or extend method, then follow blokeley's advice to be explicit.

Dingle
yes, that's what I did
afriza