#22672 closed Uncategorized (duplicate)

ManyToMany insert fails with integrity error when a foreign key is empty string

Reported by: leetreveil@… Owned by: nobody
Component: Database layer (models, ORM) Version: 1.6
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

How to reproduce:

class Tag(models.Model):
    id = models.CharField(_(u'id'), max_length=128, primary_key=True)

class Post(models.Model):
    tags = models.ManyToManyField(Tag, blank=True, null=True)
post_obj = Post.objects.get(id='someid')
tag_obj = Tag.objects.get(id='')
post_obj.tags.add(tag_obj)

So when adding a tag object with it's id as a empty string (which is valid) will fail with django.db.utils.IntegrityError: (1048, "Column 'tag_id' cannot be null").

Looking into the generated sql tag_id is being converted to NULL:

INSERT INTO `post_tags` (`post_id`, `tag_id`) VALUES ('someid', NULL)

How do we stop the orm from converting tag_id to NULL and allow it to stay as a empty string?

Change History (3)

comment:1 Changed 16 months ago by anonymous

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

You are allowing null values in your Post model, documentation https://docs.djangoproject.com/en/dev/ref/models/fields/#null says that doing that, blank values will be stored as NULL into the db.

Saying that you have a primary_key which can be empty in your Tag model but cannot be NULL as per pk nature (see python manage.py sql yourapp for tags)

See also how the middle table post_tags is built to have a better idea why it's failing for your case. I think ORM is doing the right thing here

comment:2 Changed 16 months ago by leetreveil@…

Hi, thanks for the reply.

NULL on a ManyToMany field has no effect, see: http://stackoverflow.com/questions/18243039/south-migrating-foriegn-key-many-to-many-field-to-null-true-blank-true-doesnt

I'm pretty sure this is related to: https://code.djangoproject.com/ticket/19299

comment:3 Changed 15 months ago by bmispelon

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

Hi,

I believe this issue was fixed with 8bbdcc76e4a84cde92b8dbfd01581d098bd2187d which will be part of the 1.7 release.

Consequently, I'm going to mark this ticket as duplicate of #19299.

Thanks.

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