Saturday, October 29, 2016

Django 1.10 "Cannot force an update in save() with no primary key", using model with composite primary key (unique_together)

Hi all,

I have a simple model whichs acts as custom many-to-many association table with additional data.

```
class NetworkLinkAssociation(models.Model):
    """
    We use our own many-to-many association table, because we want to keep
    track which links are added, and which links are deleted/disabled in
    comparison to the parent network.
    """

    network = models.ForeignKey('Network', related_name='links_assoc',
                                on_delete=models.CASCADE)
    link = models.ForeignKey('Link', related_name='networks_assoc',
                             on_delete=models.CASCADE)

    type = enum.EnumField(AssociationType, default=AssociationType.UNCHANGED,
                          null=True)

    class Meta:
        unique_together = ('network', 'link')

    @property
    def link_disabled(self):
        return self.type == AssociationType.REMOVED
```

When trying to simply create a new object django raises an error:

```
link_assoc = NetworkLinkAssociation()
link_assoc.link = link
link_assoc.network = network
link_assoc.save()
```

"ValueError: Cannot force an update in save() with no primary key.".

I'm 100% sure the `link` and `network` objects exist, so what else could the problem be? This used to work fine Django 1.9.

Possibly related bug on Github: https://github.com/jpwatts/django-positions/issues/49

Thanks in advance,
Lucas

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/a8397f59-203f-40e5-a6b2-ee850f50b83e%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment