Opened 2 years ago

Closed 2 years ago

#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


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='')

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 2 years ago by anonymous

Needs documentation: unset
Needs tests: unset
Patch needs improvement: unset

You are allowing null values in your Post model, documentation 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 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 2 years ago by leetreveil@…

Hi, thanks for the reply.

NULL on a ManyToMany field has no effect, see:

I'm pretty sure this is related to:

comment:3 Changed 2 years ago by Baptiste Mispelon

Resolution: duplicate
Status: newclosed


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.


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