Django:有两个字段是唯一的,但是仍然不能使用unique-constraint

2024-04-23 12:13:23 发布

您现在位置:Python中文网/ 问答频道 /正文

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

    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。当我把剩下的呕吐物都吐出来时,它指向second_post.save()。但是,assertNotEqual始终通过,如果我将其更改为assertEqual,则失败。在

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

以下是博客模式供参考:

^{pr2}$

Tags: the模型标题datetitleissavetags
1条回答
网友
1楼 · 发布于 2024-04-23 12:13:23

模型中的字段名为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()

相关问题 更多 >