Home > Back-end >  How to run _icontains method on a foreignkey field in django
How to run _icontains method on a foreignkey field in django

Time:05-26

I am building a dummy E-commerce site. For this, I wish to build a staff portal where I can search for pending orders by a user's first name. I have made a foreignkey field on my model that I am referencing. But when I use the __icontains method in my views on user field, I get Related Field got invalid lookup: icontains error. I wish to return all orders that have been made by a user that have a certain searched string in their first name.

My 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)

My Order model:

    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)

The user model is the standard django.contrib.auth.models user model

CodePudding user response:

Well icontains doesn't work with relationships but with field of the related model:

searched_pending_orders = orders.filter(user__username__icontains=search_query)

Will works perfectly.

  • Related