Skip to content

Commit

Permalink
Still generate uniqueness lookups when a uniqueness field is empty.
Browse files Browse the repository at this point in the history
In our specific example, we have Sections, with uniqueness on the tuple
of (parent, instance). parent is optional and can be None, but we still
want uniqueness of the tuple when that is the case.
  • Loading branch information
dracos committed Jan 30, 2014
1 parent c070f42 commit 4070cc2
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 4 deletions.
6 changes: 6 additions & 0 deletions sluggable/tests/models.py
Expand Up @@ -42,3 +42,9 @@ class DayPost(models.Model):
date = models.DateField()
slug = SluggableField(unique_with='date')
slugs = generic.GenericRelation(PostSlug)

class WordPost(models.Model):
user = models.ForeignKey(User)
word = models.CharField(max_length=50, blank=True)
slug = SluggableField(unique_with=('user', 'word'))
slugs = generic.GenericRelation(PostSlug)
17 changes: 16 additions & 1 deletion sluggable/tests/tests.py
Expand Up @@ -4,7 +4,7 @@

from django.test import TestCase

from .models import Poll, PollSlug, UserSlug, User, Post, DayPost, PostSlug
from .models import Poll, PollSlug, UserSlug, User, Post, DayPost, WordPost, PostSlug


class SluggableTests(TestCase):
Expand Down Expand Up @@ -174,3 +174,18 @@ def test_unique_with(self):

def test_unique_with_date(self):
self._unique_with(DayPost, 'date', date(2014, 1, 1), date(2014, 2, 1))

def test_unique_with_blank_word(self):
user = User.objects.create(username='matthew')

post1 = WordPost.objects.create(user=user, word='word', slug='a-slug')
post2 = WordPost.objects.create(user=user, word='word', slug='a-slug')
post3 = WordPost.objects.create(user=user, word='', slug='a-slug')
post4 = WordPost.objects.create(user=user, word='', slug='a-slug')

self.assertEquals(PostSlug.objects.count(), 4)

self.assertEquals(post1.slug, 'a-slug')
self.assertEquals(post2.slug, 'a-slug-2')
self.assertEquals(post3.slug, 'a-slug')
self.assertEquals(post4.slug, 'a-slug-2')
4 changes: 1 addition & 3 deletions sluggable/utils.py
Expand Up @@ -100,9 +100,7 @@ def get_uniqueness_lookups(field, instance, unique_with):
% (instance._meta.object_name, field_name))

value = getattr(instance, field_name)
if not value:
if other_field.blank:
break
if not value and not other_field.blank:
raise ValueError('Could not check uniqueness of %s.%s with'
' respect to %s.%s because the latter is empty.'
' Please ensure that "%s" is declared *after*'
Expand Down

0 comments on commit 4070cc2

Please sign in to comment.