在 Django-Rest 数据表上过滤外键

Filter into Foreign Keys on Django-Rest Datatables

我有一个 Order 模型的数据表,其中包含 User 模型中的一些字段,并使用序列化程序实现,如下所示

serializers.py

# customer order detail serializer
class CustomerOrderSerializer(serializers.ModelSerializer):
    first_name = serializers.ReadOnlyField(source='user.first_name')
    last_name = serializers.ReadOnlyField(source='user.last_name')

    def __init__(self, *args, **kwargs):
        remove_fields = kwargs.pop('remove_fields', None)
        super(CustomerOrderSerializer, self).__init__(*args, **kwargs)

        if remove_fields:
            for field_name in remove_fields:
                self.fields.pop(field_name)

    class Meta:
        model = Order
        fields = ['id', 'amount', 'order_status', 'created', 'first_name', 'last_name']
        read_only_fields = ['issue_date', 'first_name', 'last_name']

views.py

class OrderList(generics.ListAPIView):
    queryset = Order.objects.order_by('-created')
    serializer_class = CustomerOrderSerializer

我成功获得了 first_namelast_name 字段,如图所示的数据表格式

但是,我的要求 是 filter/search 在字段 first_name & last_name 的数据表中,它们来自不同的模型 User

当我尝试过滤这些字段时,我得到 以下错误:

Cannot resolve keyword 'first_name' into field. Choices are: ..., .., ..., .. 

任何人都可以帮助我理解,我们如何过滤 django-rest 数据表中的外键字段

您可以使用 SearchFilter.doc

from rest_framework import filters

class OrderList(generics.ListAPIView):
    queryset = Order.objects.order_by('-created')
    serializer_class = CustomerOrderSerializer
    filter_backends = [filters.SearchFilter]
    search_fields = ['user__first_name', 'user__last_name']

之后,您可以通过 ?search=foo 查询参数搜索名字和姓氏。