Search code examples
djangodjango-modelsdjango-querysetdjango-orm

Get n value with n parameter with Django Queryset


this is my first question. If my question is not clear, let me know :)

So I learn Django (learning by doing) for 4 Months in my project. I have one table name material, which is the table contains material name and price. Here I will describe my table:

id materialName price
1 Not Required 0
2 Material 1 123
3 Material 2 456
4 Material 3 900

I want to calculate the total material price by getting the price from the table. It looks ok if I only want to get 1 price only. But, I need to get 4 values of prices from what the user wants in input. Let's say the user chooses Material 3, Material 2, Not Required and Not Required. So there is 4 material price. Then, I use a queryset like this:

x = rawmaterial.objects.filter(Q(materialName = 'Material 3') | Q(materialName = 'Material 2') | Q(materialName = 'Not Required') | Q(materialName = 'Not Required')).values_list('price',flat=True)

but the result is (900, 456, 0) not like (900, 456, 0, 0). I have been trying with SQL query using OR, is there any possibility to get 4 values? Thank you :)


Solution

  • You can't query like that. Filter will filter out the values, not make them 0. Instead, you can use Conditional Expression. In your case, you can consider Case:

    from django.db.models import Case, Value, When, F
    
    rawmaterial.objects.annotate(
         required_prices=Case(
             When(materialName__in =['Material 3','Material 2', 'Not Required'], then=F('price')),
             default=Value(0),
         )
    ).values_list('required_prices', flat=True)
    

    FYI, please follow the pep-8 style guide for naming class name (Pascal Case) and field/function names (snake case).