Meta.fields包含一个未在此FilterSet上定义的字段:****

时间:2016-10-16 14:49:47

标签: django django-models django-filter

我正在使用Django Filters软件包。

我在视图中以下列方式定义我的过滤器

class UnitFilter(django_filters.FilterSet):
    class Meta:
        model = Unit
        fields = [
            'floor', 'number', 'building','lease','leaseterm', 
            'lease__is_active','lease__is_terminated','lease__is_renewed',]

我过滤的我的单位模型是

class Unit(CommonInfo):
    version = IntegerVersionField( )
    number = models.CharField(max_length=30,null=True, blank=True)
    max_occupants = models.PositiveSmallIntegerField()
    floor = models.PositiveSmallIntegerField()
    rooms = models.PositiveSmallIntegerField()
    is_disabled_access = models.BooleanField(default=False)
    balcony_quantity = models.PositiveSmallIntegerField()
    building = models.ForeignKey(Building)
    recomended_price = models.DecimalField(max_digits=7, decimal_places=2)
    _lease = None
    _leaseterm = None
    #check = models.ManyToManyField(UnitCheck, through='UnitChecklist')

    def _get_total(self):

        from conditions.models import LeaseTerm
        from lease.models import Lease

        lease_dict = Lease.objects.filter(unit_id=self.id, is_active = True , is_terminated = False).aggregate(Max('id'))
        if lease_dict['id__max']:
            lease =  lease_dict['id__max'] 
        else:  
            lease =  0

        leaseterm_dict = LeaseTerm.objects.filter(lease_id=lease, is_active = True , is_terminated = False).aggregate(Max('id'))
        if leaseterm_dict['id__max']:
            leaseterm =  leaseterm_dict['id__max'] 
        else:  
            leaseterm =  0

        self._lease = lease
        self._leaseterm = leaseterm

    @property
    def lease(self):
        if self._lease is None:
            self._get_total()
        return self._lease

    @property
    def leaseterm(self):
        if self._leaseterm is None:
            self._get_total()
        return self._leaseterm

此模型中有2个计算属性 租赁和租赁期

当leaseterm给我这个错误时,

lease属性没有问题

  

Meta.fields包含未在此FilterSet上定义的字段:   leaseterm

为什么呢?它是django-filter中的一个错误?有什么解决方法吗?

1 个答案:

答案 0 :(得分:7)

有关详细说明,请参阅this

当您执行queryset.filter(field_name=field_value)时,Django会将其转换为SQL查询。遗憾的是,计算出的属性仅存在于Python对象上,因此您无法通过它们进行过滤。

解决方法是,每当您按其中一个进行过滤时,请在查询集中包含一个注释,该注释会在SQL中添加适当的字段。该链接有一个很好的例子,说明如何做到这一点。它比在Python中更难,但唯一的方法就是去。