在Django模型中测试“类元” [英] Testing 'class Meta' in Django models

查看:82
本文介绍了在Django模型中测试“类元”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Django模型中测试排序唯一唯一_

How can you test ordering, unique and unique_together in Django models?

推荐答案

如MDN Django教程第10部分所述,您应该测试自己代码的所有方面,但不要 Python或Django。请参见 MDN应该测试的内容 。要测试您编写的内容,您应该访问模型类的meta属性和模型的字段。例如,按如下方式定义书籍模型:

As stated in the MDN Django Tutorial Part 10, "You should test all aspects of your own code, but NOT any libraries or functionality provided as part of Python or Django." See MDN's what you should test. To test what was written by you, you should access the meta attribute of the model class and the model's fields. For example, having defined the book model as follows:

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey('Author', on_delete=models.SETNULL, null=True)
    isbn = models.CharField('ISBN', max_length=13, unique=True)

    class Meta:
        unique_together(('title', 'author'),)
        ordering = ['author']

将对Book模型进行单元测试,确定其唯一性,唯一性和顺序,如下所示:

The Book model would be unit tested for unique, unique_together, and ordering as follows:

class BookModelTests(TestCase):
    @classmethod
    def setUpTestdata(cls):
        #create an author instance and a book instance

    def test_isbn_is_unique(self):
        book = Book.objects.get(id=1)
        unique = book._meta.get_field('isbn').unique
        self.assertEquals(unique, True)

    def test_book_is_unique(self):
        book = Book.objects.get(id=1)
        unique_together = book._meta.unique_together
        self.assertEquals(unique_together[0], ('title', 'author'))

    def test_book_ordering(self):
        book = Book.objects.get(id=1)
        ordering = book._meta.ordering
        self.assertEquals(ordering[0], 'author')

这篇关于在Django模型中测试“类元”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆