Opened 11 years ago

Closed 11 years ago

#5660 closed (invalid)

inconsistent behavior of explicit primary_key and ManyToManyField

Reported by: zeliboba7@… Owned by: nobody
Component: Uncategorized Version: master
Severity: Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


In some cases explicit primary_key allows to use it for ManyToManyField relation before .save(), in others not. See example

from django.db import models

class Author(models.Model):
    name = models.CharField(maxlength=50)

class Reference(models.Model):
    >>> a = Author(name='some name')
    >>> r = Reference(title='some title')
    >>> r.authors.add(a)
    id = models.CharField(maxlength=5, primary_key=True)
    title = models.CharField(maxlength=50)
    authors = models.ManyToManyField(Author)

The doctest passed, since I specified primary_key explicitly and it works without before adding Author. but if you'll change id field to

    id = models.AutoField(primary_key=True)

or to

    id = models.IntegerField(primary_key=True)

the doctest fails. the only cure is using before before r.authors.add(a) or
r = Reference.objects.create(title='some title')
I tried both on django-0.96 and svn version with sqlite3 backend

Change History (1)

comment:1 Changed 11 years ago by Jacob

Resolution: invalid
Status: newclosed

You should never be able to add objects to an M2M if either object isn't saved yet. The only reason this works at all with the CharField is that id gets set to "" (the empty string) by default. You always need to save() before added related objects.

Note: See TracTickets for help on using tickets.
Back to Top