0

I'm trying to add an instance of a model in Django to a list and get these results (from Shell):

  1. Import the model and instantiate an object
>>> from base.models import Service
>>> s = Service.objects.first()
  1. Check the type of the object
>>> type(s) 
<class 'base.models.Service'> 
  1. Instantiate the list
>>> mylist = []
  1. Try to add the model object to the list
>>> mylist += s 
  1. Error
Traceback (most recent call last): 
  File "<console>", line 1, in <module>
TypeError: 'Service' object is not iterable

Why exactly can I not add a model instance to the list?

Zack Plauché
  • 3,307
  • 4
  • 18
  • 34

2 Answers2

3

You have three options:

mylist += [s]

or:

mylist.append(s)

or:

mylist.extend([s])

Why do you get your error?

mylist += s is same as mylist.extend(s) which fails if the one adding is non-iterable. Whereas wrapping s in squares brackets makes it a <class 'list'> which is now iterable. Thus, mylist += [s] works in the same way mylist.extend([s]) also works.

Austin
  • 25,759
  • 4
  • 25
  • 48
2

You should use

mylist.append(s)

instead. Remember that you're basically doing

mylist = mylist + s

and, by definition of the + operator on lists, the s must be an iterable object as well.

See here for a better explanation of the + operator (or .extend()) vs append.

Kevin Languasco
  • 2,318
  • 1
  • 14
  • 20