Вопрос

My question is similar to Django Advanced Filtering but I need another approach:

Abstract:

  • Tables: manufacturer, supplies
  • Manufacturers have multiple supplies (1 or 0 in "supply" table)

I have a HTML form with multiple (20+ checkboxes) which should limit the queryset with AND queries (so standard). The HTML checkbox names equal MySQL field names. My table looks like this:

mysql> explain supply;
+----------------------+------------+------+-----+---------+----------------+
| Field                | Type       | Null | Key | Default | Extra          |
+----------------------+------------+------+-----+---------+----------------+
| id                   | int(11)    | NO   | PRI | NULL    | auto_increment |
| manufacturer_id      | int(11)    | NO   | MUL | NULL    |                |
| supply1              | tinyint(1) | NO   |     | NULL    |                |
| supply2              | tinyint(1) | NO   |     | NULL    |                |
| supply3              | tinyint(1) | NO   |     | NULL    |                |
| [...]                | tinyint(1) | NO   |     | NULL    |                |
| supply20             | tinyint(1) | NO   |     | NULL    |                |

Now in pseudo SQL, I'd like to:

  • User selected checkboxes supply2 and supply14: SELECT * FROM supply WHERE supply2 = 1 AND supply14 = 1;
  • User selected checkboxes supply1, supply9 and supply18: SELECT * FROM supply WHERE supply1 = 1 AND supply9 = 1 AND supply18 = 1;

I'm pretty sure I need some QuerySet with kwargs, but I'm unable to construct the view for my needs (still learning Django).

Это было полезно?

Решение

I wonder if the data model here couldn't use some tweaking? You might want to have a supply table with twenty rows and an intermediate table connecting them (that is a ManytoMany(Supply) or something like that). Then you could just have a multi select field, rather than 20 check boxes (unless you really need them for some other reason).

If you need to add another supply, it's simply adding another row, rather than a schema migration.

Другие советы

supplies = Supply.objects.filter( supply1 = 1 )

And if you want to filter again:

supplies = supplies.filter(supply2 = 1) 

The filter() method returns a QuerySet, so you can chain as many filter() calls as you like.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top