Opened 6 years ago

Closed 6 years ago

#30210 closed New feature (wontfix)

Allow empty strings of blank=True model fields to pass unique_together constraint

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

Description

I've been researching this one a little, and this is what I found: https://stackoverflow.com/questions/454436/unique-fields-that-allow-nulls-in-django

Here is what I am trying to accomplish:

class MyModel(models.Model):
    my_foreignkey = models.ForeignKey(
        'ForeignKeyModel',
        on_delete=models.CASCADE
    )
    my_charfield = models.CharField(
        'My Field',
        max_length=100,
        blank=True
    )
    field = models.CharField(
        max_length=100
    )
    
    class Meta:
        unique_together = ('my_foreignkey', 'my_charfield')
        

FOREIGN_KEY = ForeignKeyModel.objects.get(id=1)
        
MyModel.objects.create(
    my_foreignkey=FOREIGN_KEY,
    field='Field 1',
    my_charfield=''
)

# This raises unique_together error.
MyModel.objects.create(
    my_foreignkey=FOREIGN_KEY,
    field='Field 2',
    my_charfield=''
)

It does appear as though there is enough interest in the issue. Is this unrealistic?

Change History (1)

comment:1 by Tim Graham, 6 years ago

Component: UncategorizedDatabase layer (models, ORM)
Resolution: wontfix
Status: newclosed
Type: UncategorizedNew feature

A solution would require Django to change input data from empty strings to nulls. This would be backwards incompatible and often undesired. See stackoverflow for possible solutions you can implement for the use case.

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