我想知道我是否可以使用序列化程序添加数据库的两列,将其打包,并作为奖励过滤器。
模型.py
class Snippet(models.Model):
time1= models.DateTimeField()
time2 = models.DateTimeField()
序列化程序.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))
视图.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>4
编辑:
显然,我无法通过序列化字段进行过滤。所以让我修改我的问题,我可以按 time1 过滤吗,除非我将时间从我的网站输入到 API,我使用的是 EPOCH 时间,而不是 time1,DATETIME 谢谢@mariodev