Задать вопрос

Тел: +7 965 3737 888

441

Просмотров

2

Ответов

CategoriesField

<p>If you have a relatively small finite number of categories (e.g. &lt; 64), don't want to add a separate column for each one, and don't want to add an entire separate table and deal with joins, this field offers a simple solution.</p>
<p>You initialize the field with a list of categories. The categories can be any Python object. When saving a set of categories, the field converts the set to a binary number based on the indices of the categories list you passed in. So if you pass in as your categories list [A,B,C,D] and set model.categories = [C,D], the integer stored in the database is 0b1100 (note that although the categories list has a left-to-right index, the binary number grows right-to-left).</p>
<p>This means that if you change the order of your category list once you have data in the DB, you'll need to migrate the data over to the new format. Adding items to the list should be fine however.</p>
<p>If you need to do filtering based on this field, you can use bitwise operators. Django currently (to my knowledge) doesn't support this natively, but most DBs have some bitwise operator support and you can use the extra function for now. For example, this query will select CheeseShop models that have the 'Gouda' in its cheeses field.</p>
<p>CheeseShop.objects.all().extra(where=['cheeses | %s = cheeses'], params=[CHEESES.index('Gouda')])</p>

Вопрос полезен? Да0/Нет0
file_5177.py(2.3Кб)
None

Ответы (2):

Ответm0nonoke:31.07.2009
Ответ полезен? Да0/Нет0

What's wrong with using the standard field option choices?

Ответgregb:30.07.2009
Ответ полезен? Да0/Нет0

I'm a bit baffled as to why you'd do this rather than just a simple Category model with ManyToMany relationship. Seems to be overly complicated and not really adding anything...

Have I missed something?