'How can I count how many products are ordered by a single user?

This is a single-page website that is kinda ecommerce site. I just want to count a single user how many products are ordered. How can I count?

index view:

def index(request):
    total_user = User.objects.count()-1
    total_orders =Frontend_Order.objects.count()
    context = {
        "total_user":total_user,
        "total_orders":total_orders
    }
    return render(request,'0_index.html',context)

frontend_view:

def frontend_orders(request):
    if request.user.is_authenticated:
    
        if request.method == "POST":
            frontend_orders_request = request.FILES['frontend_file'] if 'frontend_file' in request.FILES else None
            sections = request.POST.get('numField11')
            functionality = request.POST.get('frontend')

            if functionality == "Portfolio":
                price = int(sections)*10
            elif (functionality == "e-Commerce") or (functionality == "social-media"):
                price = int(sections)*15
            
            Frontend_Order.objects.create(
                files = frontend_orders_request,
                Number_of_Section = sections,
                Website_Functionality = functionality,
                Price = price, USer = request.user,
                Email = request.user.email
                )

            messages.success(request,f"{request.user.first_name}, Your order is procecing. I'll cotact you before placing the order.")
            
            return redirect("/", userz = request.user)
    else:
        messages.error(request,"Please login or create an account.")

        
    return redirect("/")

Frontend Order Model:

class Frontend_Order(models.Model):
    USer = models.CharField(max_length=50, null=True)
    Price = models.CharField(max_length=250, null=True)
    Number_of_Section = models.CharField(max_length=250, null=True)
    Website_Functionality = models.CharField(max_length=1, null=True)
    Email = models.EmailField(max_length=50, null=True)
    files = models.FileField(upload_to="new_file/", null=True, blank=True)

    def __str__(self):
        return str(self.pk)+ str(".") + str(self.USer)


Solution 1:[1]

You should use Frontend_Order.objects.filter(USer=userid) (or Frontend_Order.objects.filter(USer.id=userid) if it didn't worked) to get user orders by it's user id and then, use a for loop and a counter variable to iterate on filtered orders and add their products count to the counter.

It is better to reconsider your chosen names.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Erfan Saberi