django通过派生字段进行restful过滤

时间:2013-10-15 20:19:29

标签: django django-rest-framework

我想知道我是否可以使用序列化程序添加数据库的两列,将其打包,并作为奖励过滤器。

models.py

class Snippet(models.Model):
    time1= models.DateTimeField()
    time2 = models.DateTimeField()

serializers.py

class SnippetSerializer(serializers.ModelSerializer):
    sometime= UnixEpochDateField(source  = 'time1') # special serializer that converts a datetime to epoch (below)
    sometime2= UnixEpochDateField(source  = 'time2') # special serializer that converts a datetime to epoch (below)

    sometime_SUM = sometime + sometime2 # THIS DOES NOT WORK!

    class Meta:
        model = Snippet
        fields = ('sometime_SUM')

class UnixEpochDateField(serializers.DateTimeField):
    def to_native(self, value):
        """ Return epoch time for a datetime object or ``None``"""
        import time
        try:
            return calendar.timegm(value.utctimetuple())
        except (AttributeError, TypeError):
            return None

    def from_native(self, value):
        import datetime
        try:
            value = float(value)
        except:
            raise serializers.ValidationError("Not a number.  Input: %s %s"%(type(value), value))
        if value < 0:
            raise serializers.ValidationError("Cannot be less than 0. Input: %s"%value)

        return datetime.datetime.utcfromtimestamp(float(value))

views.py

class SnippetList(APIView):
    """
    List all snippets, or create a new snippet.
    """
    filter = ('sometime_SUM') # THIS DOES NOT WORK!
    def get(self, request, format='json'):
        snippets = Snippet.objects.all()
        filter = SnippetFilter(request.GET, queryset = snippets)  # THIS DOES NOT WORK!
        serializer = SnippetSerializer(filter, many=True)
        return Response(serializer.data)

我已经突出显示了我天真以为无效的代码 我想使用的url命令是/ someurl / snippets /?sometime_SUM&gt; 4

编辑:
显然,我无法通过序列化字段进行过滤。所以让我修改我的问题,我可以按时间过滤,除非我从我的网站输入时间到API,我使用EPOCH时间,而不是time1,DATETIME 谢谢@mariodev

0 个答案:

没有答案