我有一个模特:
class Call(models.Model):
created_on = models.DateTimeField(auto_now_add=True)
send_on = models.DateTimeField(default=datetime.now)
...
survey = models.ForeignKey(Survey, null=True, blank=True)
和相应的ModelSerializer:
class CallSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(
view_name='call-detail',
)
recipient = PhoneNumberField(read_only=False)
status = SurveySerializer(source='survey', read_only=True)
class Meta:
model = Call
fields = ('url', 'id', 'send_on', ...)
lookup_field= 'pk'
并查看:
class CallList(generics.ListCreateAPIView):
serializer_class = CallSerializer
permission_classes = (permissions.IsAuthenticatedOrReadOnly, IsOwnerOrSuperuser,)
def pre_save(self, obj):
...
def get_queryset(self):
"""
This view should return a list of all the calls
for the currently authenticated user.
"""
...
我希望能够支持API列表请求,让调用者按Call
的日期范围过滤send_on
。我不确定如何以RESTful方式执行此操作以及DRF应该以何种方式执行此操作,但是类似这样的事情:
mydomain.com/call/?start=2013-11-25T12:50:17&end=2013-11-28T12:50:17
并且返回将在给定日期之间列出send_on
的所有呼叫。使用DRF实现此目的的正确方法是什么?
答案 0 :(得分:5)
我认为在DRF文档中here清楚地解释了这一点。
所以在你的情况下,它看起来像:
from dateutil.parser import parse
class CallList(generics.ListCreateAPIView):
# ...
def get_queryset(self):
filter = {}
queryset = Call.objects.all()
start_date = self.request.QUERY_PARAMS.get('start_date', None)
end_date = self.request.QUERY_PARAMS.get('end_date', None)
if start_date is not None:
filter['send_on__gte'] = parse(start_date)
if end_date is not None:
filter['send_on__lte'] = parse(end_date)
queryset = queryset.filter(**filter)
return queryset
我使用python-dateutil轻松解析iso格式化的日期时间。