0

aren't instances of class iterable in python as it is possible in java ,.,

class User(models.Model):
    first_name =  models.CharField(max_length=50)
    ref_num = models.IntegerField()



ref_list = [2,3]
user_list = [User(first_name='abc',ref_num=1)]

for ref in ref_list:
    user_list.extend(User(first_name='abc',ref_num=ref))

but getting error as :

TypeError 'User' object is not iterable

3
  • 2
    Use .append not .extend... Commented Jun 1, 2014 at 15:41
  • 1
    To elaborate, extend takes the contents of a list, item for item, and appends them to another list. append adds an item to the end of a list. Therefore, extend expects to get a listlike as its input, whereas append will take anything. Commented Jun 1, 2014 at 15:46
  • @aruisdante thanx for detailed explaination on append's behaviour... Commented Jun 1, 2014 at 16:00

1 Answer 1

2

If you want to add a single instance of an object, then you can use .append, but in this case you may as well build a generator and .extend the list, eg:

ref_list = [2,3]
user_list = [User(first_name='abc',ref_num=1)]

user_list.extend(User(first_name='abc', ref_num=ref) for ref in ref_list)

Remember though, that unless you .save() those model objects, they won't persist in your DB.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.