Django Rest Framework过滤计算的模型属性 [英] Django Rest Framework filtering calculated model property

查看:176
本文介绍了Django Rest Framework过滤计算的模型属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉有一个新手问题.我有以下模型:

Sorry for a newbie question. I have a following model:

class WeightSlip(models.Model):

    grossdate = models.DateTimeField(auto_now=False, auto_now_add=False)
    grossweight = models.DecimalField(max_digits=6, decimal_places=2, default=0)
    taredate = models.DateTimeField(auto_now=False, auto_now_add=False)
    tareweight = models.DecimalField(max_digits=6, decimal_places=2, default=0)
    vehicle = models.CharField(max_length=12)

    @property
    def netweight(self):
        return self.grossweight - self.tareweight

    @property
    def slipdate(self):
        if self.grossdate > self.taredate:
           return grossdate.date()
        else:
           return taredate.date()

序列化器:

class WeightSlipSerializer(serializers.ModelSerializer):

   class Meta:
      model = models.WeightSlip
      fields = ('grossdate', 'grossweight', 'taredate', 'tareweight', 'slipdate', 'netweight', 'vehicle')
      read_only_fields = ('slipdate', 'netweight')

我正在尝试使用 django-rest-framework-filters 来过滤计算出的净重"和滑动日期"属性:

I am trying to use the django-rest-framework-filters to filter on the calculated 'netweight' and 'slipdate' properties:

class WeightSlipFilter(FilterSet):

   class Meta:
       model = WeightSlip
       fields = ('slipdate', 'netweight', 'vehicle')

这给了我一个错误:

TypeError: 'Meta.fields' contains fields that are not defined on this FilterSet: slipdate, netweight

除了将计算出的字段添加到数据库之外,是否有解决此问题的方法?

Is there a workaround to this problem other than adding the calculated fields to the database ?

谢谢.

推荐答案

您可以为slipdate, netweight创建自定义过滤器,该过滤器将评估和过滤db中的该字段.为此,您可以使用条件表达式 F表达式

You can create custom filter for slipdate, netweight that will evaluate and filter this fields in db. For this you can use conditional expressions and F expression

from django.db.models import F, Case, When

class WeightSlipFilter(FilterSet):
    slipdate = DateTimeFilter(method='filter_slipdate')
    netweight = NumberFilter(method='filter_netweight')

    class Meta:
        model = WeightSlip
        fields = ('slipdate', 'netweight', 'vehicle')

    def filter_netweight(self, queryset, value):
        if value:
            queryset = queryset.annotate(netweight=F('grossweight') - F('tareweight')).filter(netweight=value)
        return queryset

    def filter_slipdate(self, queryset, value):
        if value:
            queryset = queryset.annotate(slipdate=Case(When(grossdate__gt=F('taredate'), then=F('grossdate')), default=F('taredate')).filter(slipdate=value)
        return queryset

这篇关于Django Rest Framework过滤计算的模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆