根据DateField和TimeField过滤模型

时间:2016-12-06 12:54:57

标签: django django-models django-rest-framework django-serializer

我有一个类似以下的事件模型;

class Event(models.Model):
    name = models.CharField(max_length=50)
    date = models.DateField(null=True)
    start = models.TimeField(null=True)
    location = models.CharField(max_length=255)
    creator = models.ManyToManyField(User, related_name='event_creator')
    info = models.CharField(max_length=255, default='')
    users = models.ManyToManyField(EventUser, blank=True)

    def __str__(self):
        return self.name

这是我的序列化器

class EventSerializer(serializers.ModelSerializer):
    users = UserListingField(many=True, read_only=True)
    creator = serializers.SlugRelatedField(many=True, read_only=True, slug_field='username')

    class Meta:
        model = Event
        fields = '__all__'

但我想只获得不过时的事件而不是所有事件。我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:0)

如果您在DRF Generic View中使用序列化程序,则可以设置queryset属性或使用get_queryset方法:

class MyListView(ListAPIView):

    serializer_class = EventSerializer
    queryset = Event.objects.filter(<your filter conditions>)

或者,使用get_queryset方法:

class MyListView(ListAPIView):

    serializer_class = EventSerializer

    def get_queryset(self):
        queryset = Event.objects.filter(<your filter conditions>)
        return queryset