Skip to main content
 首页 » 编程设计

python之Django:两个字段是唯一的,但仍未通过 UNIQUE 约束

2024年08月23日30softidea

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

    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 它会失败。

无论我在 title 值中输入什么,我都会得到同样的错误。为什么这两个 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) 

请您参考如下方法:

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