5

I'm looping through a list of objects and saving. I need the newly generated id or pointer id right after the save but it is None.

Here is my code:

for category in category_list:
      saved_category = category.save()
      print saved_category.parentCategory_ptr_id      
      print saved_category.id

This saves my object after the routine is run, but again, does not give me the id at this line.

here is my model:

class ParentCategory(models.Model):
    name = models.CharField(max_length=255)

class Category(ParentCategory):
    description = models.CharField(max_length=255)

category list was created like so:

category_list = []
    for row in value_list:
        category = Category(description=row.description)
        category_list.append(category)


 return category_list

What am I doing wrong?

Atma
  • 29,141
  • 56
  • 198
  • 299
  • How was `object_list` created? – Alasdair Nov 30 '13 at 19:19
  • @Alasdair I added the code for object list – Atma Nov 30 '13 at 19:25
  • "category" has a lower case "c"… is it a typo? – daveoncode Nov 30 '13 at 20:28
  • @daveoncode yes it was. – Atma Nov 30 '13 at 20:46
  • can you show how value_list was created? or give us some context what's the process here? What is returning category_list and where does the first function go? Because frankly, I believe the trouble is you don't save the category objects to begin with, so upon arriving to the second function (with save_category) they stop existing (I might be entirely wrong, I just don't have enough context here) – yuvi Nov 30 '13 at 21:25
  • @yuvi this is pulled from a CSV file. The actual category object saves in the database when the entire routine runs, it is just that I cannot get the id at the line above. – Atma Dec 01 '13 at 16:42
  • Possible duplicate of [Django Model is saved, but returns None](https://stackoverflow.com/questions/16485651/django-model-is-saved-but-returns-none) – Muhammad Faizan Fareed Nov 29 '19 at 04:20

3 Answers3

1

The problem is with:

saved_category = category.save()

It needs to be:

category = category.save()

The original saved object in the list is the object that contains the id.

Atma
  • 29,141
  • 56
  • 198
  • 299
1

Their is no need of reassign.

category.save()

When you call save() method the object is saved into database and assign id (primary key) to the object. Saving Objects Django Official

Other same question asked on Stackoverflow and correct answer by Daniel Roseman

0

I don't think the object will get saved. Seems that the object you are creating lacks sufficient data to satisfy db constraints. You might have used try-catch somewhere, you would have seen the error. Try adding blank=True, null=True to name in ParentCategory or provide a name while creating the object. I hope this works...

Arpit
  • 953
  • 7
  • 11