0

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

我查看了这些线程以了解如何检查查询集是否为空。 在 Django 中,检查空查询集的最有效方法是什么? 在 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

这是来自外壳。对于“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

我在这里做错了什么?如果查询集为空,我如何检查管理器?

非常感谢 :)

4

1 回答 1

1

在过滤之前get_query_set调用管理器,因此您需要以某种方式侵入 QuerySet 本身(或制作将进行检查的外部函数)。

于 2012-03-31T02:31:57.590 回答