Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django admin - instance needs to have a primary key value before a many-to-many relationship can be used

edit: I wasn't clear before, I am saving my object in the django admin panel, not in a view. Even when I save the object with no many-to-many relationships I still get the error.

I have a model called TogglDetails that has a ForeignKey relationship with the standard django User model and a MayToManyField relationship with a model named Tag. I have registered my models with django admin but when I try to save a TogglDetails instance I get the error in the title.

Here are my models:

class Tag(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name


class TogglDetails(models.Model):
    token = models.CharField(max_length=100)
    user = models.ForeignKey(User)
    tags = models.ManyToManyField(Tag, blank=True, null=True)

    def __unicode__(self):
        return self.user.username

    class Meta:
        verbose_name_plural = "toggl details"

As far as I can tell, there should be no issues with my models and django admin should just save the instance without any issues. Is there something obvious that I have missed?

I am using Django 1.3

like image 292
Iain Shelvington Avatar asked Jun 20 '11 14:06

Iain Shelvington


2 Answers

The answer to my question was this: Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3

The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db.

like image 58
Iain Shelvington Avatar answered Sep 22 '22 17:09

Iain Shelvington


As stated by other users:

Postgres sequences without an 'owned by' attribute do not return an id in Django 1.3

The sequences in my postgres database did not have the "Owned by" attribute set and so did not return an id when a new entry was saved to the db

In addition: This is most likely caused by a backwards incompatible change that renders some primary key types in custom models beyond reach for Django 1.3. See Django trac tickets https://code.djangoproject.com/ticket/13295 and http://code.djangoproject.com/ticket/15682 for more information.

I solved the problem by running the follow commands for the affected tables/sequences.

Specifically running the command:

manage.py dbshell
ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname;

change tablename_colname_seq and tablename.colname

like image 39
Nathan Keller Avatar answered Sep 25 '22 17:09

Nathan Keller