在测试中创建对象时不调用 Django 模型的保存方法

Django model's save method is not called when creating objects in test

我正在尝试测试我的一个应用程序模型 Book,它有一个 slug 字段。我有一个自定义保存功能,如下所示。

models.py

class Book(models.Model):
    title = models.CharField(max_length=50)
    slug = models.SlugField(max_length=50, unique=True)

    def save(self, *args, **kwargs):
        if not self.slug:
            slug = slugify(self.title, allow_unicode=True)

        return super(Book, self).save(*args, **kwargs)

为了对此进行测试,我创建了以下 test.py

class BookModelTests(TestCase):

    @classmethod
    def setUpTestData(cls):
        Book.objects.create(title="Book One")

    def test_get_absolute_url(self):
        book = Book.objects.get(pk=1)
        self.assertEquals(book.get_absolute_url(), '/books/book-one/')

但是当我 运行 测试时,它失败了 django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$'].

回溯

Traceback (most recent call last):
  File "Bookman/bookman/bms/tests/test_models.py", line 14, in test_get_absolute_url
    self.assertEquals(book.get_absolute_url(), '/books/book-one/')
  File "Bookman/bookman/bms/models.py", line 26, in get_absolute_url
    return reverse('book-detail', args=[str(self.slug)])
  File "Bookman/venv/lib/python3.8/site-packages/django/urls/base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "Bookman/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 677, in _reverse_with_prefix
    raise NoReverseMatch(msg)
django.urls.exceptions.NoReverseMatch: Reverse for 'book-detail' with arguments '('',)' not found. 1 pattern(s) tried: ['books/(?P<book_slug>[-a-zA-Z0-9_]+)/$']

为什么 slug 是空的?为什么 save 方法没有被调用?我错过了什么?

您的 save 方法出现意外错误。您应该使用 self.slug 将值分配给对象的 slug,如:

def save(self, *args, **kwargs):
    if not self.slug:
        self.slug = slugify(self.title, allow_unicode=True)

    return super(Book, self).save(*args, **kwargs)