2012-03-31 3 views
0

У меня есть пользовательский менеджер для моего модельного устройства. Если возвращаемый запрос, пустой, я хочу вернуть другой объект. Проблема в том, что пустой запрос не оценивается как пустой.проверить пустые запросы в django

Я просмотрел эти темы, чтобы узнать, как проверить, что набор запросов пуст. 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-statements, чтобы проверить, является ли он пустым.

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 

И это от оболочки. Для устройств «мобильный» (который существует) и «коровы» (которых не существует) диспетчер показывает то же поведение. Когда я пытаюсь напечатать первое значение набора запросов, я получаю ожидаемый индекс 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

Управляющего get_query_set называется before filtering так что вам нужно взломать как-то в самом QuerySet (или сделать внешнюю функцию, которая будет делать проверку).

Смежные вопросы