检查django中的空查询集

时间:2012-03-31 00:05:34

标签: django django-queryset django-custom-manager

我的模型设备有自定义管理器。如果返回的查询集为空,我想返回一个不同的对象。问题是空的查询集不会被评估为空。

我研究了这些线程,以了解如何检查查询集是否为空。 In Django, what is the most efficient way to check for an empty query set? Checking for empty queryset in Django

这是我的模特:

    class DeviceField(models.Model):
    """
    Can be connected to any class and any field in that class. Specifies how the values and field names are returned for the field.
    """
    device = models.ForeignKey(Device, verbose_name=_("Device"))
    content_type = models.ForeignKey(ContentType, verbose_name=_("Class"))
    field_name = models.CharField(max_length=150, verbose_name=_("field name"))
    display_field = models.CharField(max_length=255, verbose_name=_("How to display the field name?"))
    display_value = models.CharField(max_length=255, verbose_name=_("How to display the value?"))

    objects = DeviceFieldManager()

这是我的经理。看看我如何使用所有这些if语句来检查它是否为空。

class DeviceFieldManager(models.Manager):
    """
    Behaves like a normal manager. Except in the case that no such device field exists. Then it will return the standard value of the field.
    """
    def get_query_set(self):
        """
        Does the queryset overriding :). If empty, get the original values
        """
        queryset = super(DeviceFieldManager,self).get_query_set()
        try:
            a = queryset[0]
            print "we have something here"
        except IndexError:
            print "It is frigging empty"
        if queryset == super(DeviceFieldManager, self).none():
            print "this queryset is just like an empty one"
        if not queryset:
            print "not queryset"
        if not queryset.count():
            print "not queryset count"
        if queryset:
            print "if queryset"
        if queryset.exists():
            print "queryset exists"
        else:
            print "A value is return, we don't need to do anything!"
        print queryset.count()
        print super(DeviceFieldManager, self).none()
        print queryset == super(DeviceFieldManager, self).none()
        return queryset

这是来自shell。对于“mobile”(存在)和“cow”(不存在)设备,Manager显示相同的行为。当我尝试打印查询集的第一个值时,我得到了“cow”的预期IndexError。

In [8]: a= DeviceField.objects.filter(device__name="mobile")
we have something here
if queryset
queryset exists
1
[]
False

In [9]: a[0]
Out[9]: <DeviceField: DeviceField object>

In [10]: a= DeviceField.objects.filter(device__name="cow")
we have something here
if queryset
queryset exists
1
[]
False

In [11]: a[0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/<ipython-input-11-5ccf417d7af1> in <module>()
----> 1 a[0]

/local/lib/python2.7/site-packages/django/db/models/query.pyc in __getitem__(self, k)
    188             qs = self._clone()
    189             qs.query.set_limits(k, k + 1)
--> 190             return list(qs)[0]
    191         except self.model.DoesNotExist, e:
    192             raise IndexError(e.args)

IndexError: list index out of range

我在这里做错了什么?如果查询集是空的,我怎么能检查管理器?

非常感谢:)

1 个答案:

答案 0 :(得分:1)

管理员的get_query_set被称为before filtering,因此您需要以某种方式破解QuerySet本身(或者创建将进行检查的外部函数)。