筛选空的SerializerMethodField值

时间:2019-12-02 15:40:44

标签: django-rest-framework

我有一个带有Seri​​alizerMethodField的模型序列化器,它返回相关的模型实例或None。我想过滤模型以仅返回具有此SerializerMethodField的None值的实例。

型号:

class Task(AbstractTimeStampedModel):
    game_slug = models.SlugField(
        max_length=250, blank=True
    )
    task_name = models.CharField(
        max_length=100, blank=True
    )
    celery_task_id = models.CharField(
        max_length=255,
        unique=True,
    )

    class Meta(object):
        verbose_name = ('task')
        verbose_name_plural = ('tasks')
        ordering = ('pk',)

    def __str__(self):
        return '{0}: {1} {2}'.format(
            self.celery_task_id,
            self.game_slug,
            self.task_name,
        )

序列化器:

class TaskSerializer(serializers.ModelSerializer):
    task_result = serializers.SerializerMethodField()

    def get_task_result(self, obj):
        try:
            task_result = TaskResult.objects.get(task_id=obj.celery_task_id)
            return TaskResultSerializer(task_result).data
        except (ObjectDoesNotExist, AttributeError):
            return None

    class Meta:
        model = Task
        fields = '__all__'
        read_only_fields = (
            'created',
            'updated',
            'task_result',
        )

过滤器:

class TaskFilter(filters.FilterSet):
    no_task_result = filters.BooleanFilter(field_name='task_result', lookup_expr='isnull')
    class Meta:
        model = Task
        fields = [
            'game_slug',
            'task_name',
            'celery_task_id',
            'no_task_result',
        ]

此查询GET /api/tasks/?no_task_result=True导致FieldError: Cannot resolve keyword 'task_result' into field.我缺少什么?

BTW TaskResult模型是由BTW定义的。TaskResult是从django_celery_results.models导入的,对我的Task模型一无所知。

2019年12月4日: 我现在怀疑是否可以对SerializerMethodField进行过滤。但是,此TaskViewSet @actions确实可以满足我的需求:

@action(detail=False, methods=['get'])
def pending_tasks(self, request):
    all_tasks = Task.objects.all()
    pending_tasks = []
    for task in all_tasks:
        try:
            task_result = TaskResult.objects.get(task_id=task.celery_task_id)
        except (ObjectDoesNotExist, AttributeError):
            pending_tasks.append(task)  # TaskResult does not exist
    serializer = self.get_serializer(pending_tasks, many=True)
    return Response(serializer.data)

0 个答案:

没有答案