Opened 7 years ago

Closed 6 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: UI/UX:


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

Attachments (0)

Change History (1)

comment:1 Changed 6 years ago by jacob

  • Resolution set to invalid
  • Status changed from new to closed

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.

Add Comment

Modify Ticket

Change Properties
<Author field>
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'

E-mail address and user name can be saved in the Preferences.

Note: See TracTickets for help on using tickets.