繁体   English   中英

Django:两个字段是唯一的,但仍然无法通过UNIQUE约束

[英]Django: Two fields are unique but still fail UNIQUE constraint

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

    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)

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

更改为此:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM