简体   繁体   中英

Is there a way to filter for more than one value in the same column of a table?

I am building a Website, where you can filter for beverages with many parameters, for example for the name of an Item, for the brand usw... But I also want to add a checkbox field, where you can mark certain volumes and filter my database for them.

So lets say, I want to filter by the name Cola, by brand Coca Cola and by Volume 0.7L and 1L. Now I want that all Items in my table get displayed, which have the name Cola brand Coca Cola and which have a volume of 0.7 liter and 1 liter

This does not work, because I filter for two different values in one column, which is not possible in this way, because the field "volume" can't be 0.7 and 1.

qsf = Content.objects.all().filter(Q(products__icontains=Cola) & Q(volume=0.7) & Q(volume=1) & Q(brand=Coca Cola))

I can't use the or operator (|) either, because then my filter doesn't work.

This is like my 3 post, because I don't know how to solve this problem, I really hope you guys can help me.

You should be able to use the | operator, you probably just need to use parenthesis to group the Q objects

qsf = Content.objects.all().filter(
    Q(products__icontains='Cola') &
    (Q(volume=0.7) | Q(volume=1)) &
    Q(brand='Coca Cola')
)

Apart from missing parens, I can't see what's wrong with your post, but maybe the following is better/ easier to follow.

Use multiple filter . In general, filter using Q and | for or-type selection within a column, multiple .filter for and-type selection on a different column for each filter. (You can of course and-combine multiple filter clauses in one .filter operation, and in this case I think you could also use .filter( volume__in = [0.7, 1.0] ) ).

Maybe try

 qsf = Content.objects.all(
      ).filter( products__icontains='Cola'
      ).filter( 
          Q(volume=0.7) | Q(volume=1) 
      ).filter( brand='Coca Cola'
  )

(I'm not entirely happy with this code formatting. Maybe better to close the .filter and use backslash to continue on the next line? Anyway, not relevant)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM