如何使用 pytest-django 测试 Django 查询集是否相等

How to test Django Querysets are equal using pytest-django

断言两个查询集相等的最佳/最易读的方法是什么?我提出了一些解决方案:

# option 1
assert sorted(qs1.values_list("pk", flat=True)) == sorted(qs2.values_list("pk", flat=True))

# option 2 (need to assert length first because set might remove duplicates)
assert len(qs1) == len(qs2)
assert set(qs1) == set(qs2)

我知道 Django 有一个方法 django.test.TransactionTestCase.assertQuerysetEqual. Does pytest-django have something similar? I don't see it in the documentation

它在您建议的 link 的起始行中:

Assertions
All of Django’s TestCase Assertions are available in pytest_django.asserts, e.g. from pytest_django.asserts import assertTemplateUsed

同样你可以使用,从pytest_django.asserts import assertQuerysetEqual