简体   繁体   English

如何在 Django 中测试空查询集?

[英]How can i test for an empty queryset in Django?

I'm testing a view in Django that should remove all the tags from an object.我正在 Django 中测试一个视图,该视图应该从一个对象中删除所有标签。 For that i use this assertion:为此,我使用这个断言:

self.assertEqual(list(Tag.objects.get_for_object(Animal.objects.get(pk=1))),[])

That works well, as i get an empty list in return.这很有效,因为我得到了一个空列表作为回报。 I wrapped the Django queryset in a list to avoid this:我将 Django 查询集包装在一个列表中以避免这种情况:

AssertionError: [] != []

where an empty Django queryset is compared with an empty list.将空的 Django 查询集与空列表进行比较。

But as this is not something i like a lot, i wondered if there is a nicer way to do that test.但由于这不是我很喜欢的东西,我想知道是否有更好的方法来进行该测试。

只是使用exists

self.assertFalse(Tag.objects.get_for_object(Animal.objects.get(pk=1)).exists())
self.assertEqual(Tag.objects.get_for_object(Animal.objects.get(pk=1).count(), 0)

You could also use len() if you want to enforce the queryset being evaluated as a list!如果您想强制将查询集评估为列表,您也可以使用len()

Alternately also assertQuerysetEqual is useful, you could do a comparison with an instance 0f django.db.models.query.EmptyQuerySet !或者, assertQuerysetEqual也很有用,您可以与实例 0f django.db.models.query.EmptyQuerySet进行比较! But using count() should be the fastest way in most cases!但是在大多数情况下,使用count()应该是最快的方法!

Chris's answer works in this case.克里斯的回答在这种情况下有效。 But, you can also use:但是,您也可以使用:

# the_list = list(some_queryset)   # converting a queryset into a list
self.assertEqual(len(the_list), 0)

# to go directly from queryset:
self.assertEqual(some_queryset.count(), 0)

As @Bernhard pointed, you could use self.assertQuerysetEquals , and compare your query set with an empty queryset, although it is an elegant solution, it may not be efficient.正如@Bernhard 所指出的,您可以使用self.assertQuerysetEquals ,并将您的查询集与空查询集进行比较,尽管它是一个优雅的解决方案,但它可能效率不高。

The other solutions are also valid, but here is mine:其他解决方案也有效,但这是我的:

self.assertEquals(Tag.objects.get_for_object(Animal.objects.get(pk=1), None)

I strongly suggest to don't convert a django queryset in a list.我强烈建议不要在列表中转换 django 查询集。 This is because converting a queryset to a list needs to load all the queryset in memory and convert it in a Python object.这是因为将查询集转换为列表需要将所有查询集加载到内存中并将其转换为 Python 对象。

For that purpose exist the queryset methods count() , exists() and etc..为此,存在查询集方法count()exists()等。

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

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