user1328021
user1328021

Reputation: 9830

Empty ID after when saving model to database

When I add a book model to the database, and then look at the book table in SQL Database Browser, it shows the id field as being blank.

It's strange because I have 1000 items in the table. I don't know what happened, because ~390 of them have their ID populated. The others have their id blank.

Shouldn't the id field be essentially the primary key? How could it have been populated in some cases and not other cases.

Note1: In the past I have manually deleted records -- not sure if that might be an issue. Note2: When I print "newbook id:", repr(newbook.id), the id is different than the primary key seen in SQL Database Browser.

This is what I see:

enter image description here

The relevant code is below:

Model:

class Books (models.Model):
    bookname=models.CharField(_('bookname'), max_length=255)
    publisher=models.CharField(_('publisher'), max_length=255)
    description=models.TextField(_('description'), blank=True)
    coverart = models.ImageField(upload_to="art", blank=True, null=True)
    source=models.TextField(blank=True) #source of where it came from
    last_updated=models.DateTimeField(_('added'), default=datetime.now)
    category_id=models.ManyToManyField(Category, related_name='cat')
    model = models.ManyToManyField ('model', related_name = 'model')
    shortdesc=models.TextField(_('description'), blank=True)
    url = models.TextField(_('url'), blank=True)
    uid = models.IntegerField()`

Code that saves a book:

try: 
    exists = Books.objects.get(bookname=bookname)
except Books.DoesNotExist:
    print "book does not exist -- adding now"
    newbook=Books(bookname=bookname, uid = uid, source='Mysourceofbooks',     publisher=publisher, description = description, shortdesc=shortdesc, url = url)
    newbook.save()
    for cat in category_ids:
        newbook.category_id.add(cat)
else:
    print "log: we found the book in the DB already"`

Upvotes: 1

Views: 715

Answers (2)

David Wolever
David Wolever

Reputation: 154454

As per the discussion in chat: the id column in the Book table somehow managed to lose its status as a PRIMARY KEY. Set that back and you should be good to go.

Upvotes: 2

Dingo
Dingo

Reputation: 2706

First, you can use function get_or_create for testing/saving model. It return tuple - object, created.

If you can save object with new id: set object.pk to None, and save it. In your code is more crazy thinks. => Book is better name for model that Books.

What do you think with this:

for cat in category_ids:
    print cat
    newbook.category_id.add(cat)

What is category_ids variable? Why name "category_id" for ManyToMany?

Upvotes: -1

Related Questions