Django search_fields外键无法按预期工作

时间:2019-09-26 09:45:13

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

我正在使用django_rest_api_framework。我需要搜索外键。我的搜索字段是“ customer_id”

views.py文件

class DebtListAPIView(ListAPIView):
    serializer_class = DebtCreateSerializer
    permission_classes = [IsOwner]

    filter_backends = [SearchFilter]
    list_display = ('customer_id',)
    search_fields = ["customer_id__id"]

    def get_queryset(self):
        queryset = Debt.objects.filter()
        return queryset

serializers.py文件

class DebtCreateSerializer(serializers.ModelSerializer):
    class Meta:
        model = Debt
        fields = ['id', 'user', 'customer', 'debtKey', 'created_userKey', 'total_Debt', 'received_Amount',
                  'payment_Date', 'description', ]

models.py

class Debt(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=0,
                             blank=False)    
    customer = models.ForeignKey(Customer, on_delete=models.CASCADE, blank=False,
                                 related_name='customer')  
    debtKey = models.UUIDField(editable=False, default=uuid.uuid4,
                               blank=False)
    created_userKey = models.UUIDField(editable=False,
                                       default=uuid.uuid4)
    total_Debt = models.CharField(max_length=50, blank=False)
    received_Amount = models.CharField(max_length=50, blank=True)
    payment_Date = models.DateField(blank=True)
    description = models.CharField(max_length=500, blank=True)

    created_Date = models.DateTimeField(auto_now=True)
    modified_Date = models.DateTimeField(auto_now=True)

1 个答案:

答案 0 :(得分:1)

您的字段称为class CarDict(dict): def __init__(self, car_dict=None): if car_dict is None and hasattr(self, 'DEFAULT'): car_dict = self.DEFAULT return super().__init__(car_dict) ,而不是customer

此外,我认为默认的customer_id可能比DjangoFilterBackend更合适,因为SearchFilter是用于字符串搜索查询的,例如以客户的名义。

我认为您是从Admin类复制(部分)此代码的,因为list_display也不在APIViews上执行任何操作。

将您的views.py更改为:

SearchFilter

我注意到的另一件事是您使用了混合大小写的变量,例如class DebtListAPIView(ListAPIView): serializer_class = DebtCreateSerializer permission_classes = [IsOwner] filter_backends = [DjangoFilterBackend] filter_fields = ["customer__id"] def get_queryset(self): queryset = Debt.objects.filter() return queryset payment_Datecreated_userKey。变量的python命名约定只是一个下划线,没有大写,因此您应该考虑将其更改为debtKeypayment_datecreated_user_key