문제

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?

도움이 되었습니까?

해결책

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.

다른 팁

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

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...

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top