jeudi 3 mars 2016

Django: Two fields are unique but still fail UNIQUE constraint

I am writing some test to check the model I have for a basic blog app. The model requires that blog titles be unique. The following is the body of the test I have written to save two blog posts:

    first_post.title = "First Post!"
    first_post.body = "This is the body of the first post"
    first_post.pub_date = datetime.date.today()
    first_post.tags = all_tags[0]
    first_post.slug = "first_post"
    first_post.save()


    second_post = Post()
    second_post.title = "Second Post!"
    self.assertNotEqual(first_post.title,second_post.title)
    second_post.body = "This is the body of the Second post"
    second_post.pub_date = datetime.date.today()
    second_post.tags = all_tags[1]
    second_post.slug = "second"
    second_post.save()

Note the self.assertNotEqual(first_post.title, second_post.title). I added this because when I run the test I keep getting django.db.utils.IntegrityError: UNIQUE constraint failed: blog_post.title_text. When I did through the rest of the vomitext that is spit out with this it points to second_post.save(). However, the assertNotEqual always passes, if I change it to assertEqual it fails.

No matter what I put into the title value I get the same error. Why are these two Post objects considered to have the same title?

For reference, here is the blog model:

class  Post(models.Model):
    title_text = models.CharField(max_length = 200, unique = True)
    pub_date = models.DateTimeField('date published')
    post_tags = models.ManyToManyField('Tag')
    post_body = models.TextField()
    slug = models.SlugField(max_length = 50, unique = True)

Aucun commentaire:

Enregistrer un commentaire