Login

Snippets by fongandrew

Snippet List

CategoriesField

If you have a relatively small finite number of categories (e.g. < 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. 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). 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. 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. `CheeseShop.objects.all().extra(where=['cheeses | %s = cheeses'], params=[CHEESES.index('Gouda')])`

  • field
  • categories
  • binary
Read More

Composite Indexing for MySQL

A quick and dirty hack for composite indexing if you need it. Drop this into a models.py or some other place where it'll be loaded along with the rest of Django on start up. Then add an _index_together tuple specifying the fields you want a composite index on.

  • models
  • mysql
  • composite-indexing
Read More

fongandrew has posted 2 snippets.