如何 运行 _icontains 方法在 django 中的外键字段上

How to run _icontains method on a foreignkey field in django

我正在建立一个虚拟的电子商务网站。为此,我希望建立一个员工门户网站,我可以在其中按用户的名字搜索挂单。我在我引用的模型上创建了一个外键字段。但是,当我在用户字段的视图中使用 __icontains 方法时,出现 Related Field got invalid lookup: icontains 错误。我希望 return 名字中包含特定搜索字符串的用户所下的所有订单。

我的views.py:

class delivery_staff_search_pending_orders(LoginRequiredMixin, generic.View):
    def get(self, *args, **kwargs):
        if self.request.user.groups.filter(name='Delivery_staff_admin').exists():
            search_query = self.request.GET['query']
            filter_form = PendingOrdersFilterForm()
            orders = Order.objects.filter(preproccessed=True, ordered=True, delivered=False)
            searched_pending_orders = orders.filter(user__icontains=search_query)
            context = {
                "filter_form": filter_form,
                "pending_orders_list": searched_pending_orders
            }
            return render(self.request, "staff/delivery/pending_orders.html", context)

我的订单型号:

    user = models.ForeignKey(User, on_delete=models.CASCADE)
    items = models.ManyToManyField(OrderItem)
    ref_code = models.CharField(max_length=20, default=1234)
    start_date = models.DateTimeField(auto_now_add=True)
    ordered_date = models.DateTimeField()
    ordered = models.BooleanField(default=False)
    billing_address = models.ForeignKey("BillingAddress", on_delete=models.SET_NULL, blank=True, null=True)
    coupon = models.ForeignKey("Coupon", on_delete=models.SET_NULL, blank=True, null=True)
    preproccessed = models.BooleanField(default=False)
    dispatched = models.BooleanField(default=False)
    delivered = models.BooleanField(default=False)
    Refund_requested = models.BooleanField(default=False)
    Refund_granted = models.BooleanField(default=False)
    Paid_price = models.FloatField(default=0)

用户模型是标准的django.contrib.auth.models用户模型

好吧 icontains 不适用于关系,但适用于相关模型的字段:

searched_pending_orders = orders.filter(user__username__icontains=search_query)

将完美运行。