Django:两个字段是唯一的但仍然无法使用UNIQUE约束

时间:2016-03-03 17:41:25

标签: python django unit-testing testing django-models

我正在编写一些测试来检查我的基本博客应用模型。该模型要求博客标题是唯一的。以下是我为保存两篇博客文章而编写的测试正文:

    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()

请注意self.assertNotEqual(first_post.title, second_post.title)。我添加了这个,因为当我运行测试时,我不断获得django.db.utils.IntegrityError: UNIQUE constraint failed: blog_post.title_text。当我通过其中吐出的其余vomitext时,它指向second_post.save()。但是,assertNotEqual总是通过,如果我将其更改为assertEqual则会失败。

无论我在标题值中加入什么,我都会得到同样的错误。为什么这两个Post对象被认为具有相同的标题?

供参考,以下是博客模型:

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)

1 个答案:

答案 0 :(得分:3)

模型中的字段名为title_text,但在测试中使用的是title。因此title_text的db值在两种情况下都是“”。

更改为:

first_post.title_text = "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_text = "Second Post!"
self.assertNotEqual(first_post.title_text,second_post.title_text)
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()