Storing bits as a string is not an efficient use of space and is slower to
query. Any reason why you are not using the bit datatype with a length?
E.g. 'bit(%s)' % len(self.flags)

Regards,
Michael Manfre


On Fri, Nov 1, 2013 at 3:50 PM, Paul Kenjora <[email protected]> wrote:

> Hi,
>
>   I'd like to propose a new field type I've used on several projects.  Its
> a list of boolean flags all in one field.  It replaces the need for many
> Boolean fields and has the same basic DB lookup capabilities.  This is
> fully Admin compatible and Database agnostic.
>
>   Here is the full code, I'm sure it could use some minor tweaks.
>
> from django.db import models
> from django.forms import MultipleChoiceField, CheckboxSelectMultiple
>
> class FlagField(models.Field):
>
>   description = "A set of flags."
>   __metaclass__ = models.SubfieldBase
>
>   def __init__(self, flags, *args, **kwargs):
>     self.flags = flags
>     super(FlagField, self).__init__(*args, **kwargs)
>
>   def db_type(self, connection):
>     return 'char(%s)' % len(self.flags)
>
>   def to_python(self, value):
>     if isinstance(value, list) or isinstance(value, set):
>       flagged = set(value)
>     else:
>       flagged = set()
>       for i,c in enumerate(value):
>         if c == '1' and i < len(self.flags): flagged.add(self.flags[i])
>     return flagged
>
>   def get_db_prep_value(self, value, connection, prepared=False):
>     return ''.join(map(lambda flag: '1' if flag in value else '0',
> self.flags))
>
>   def formfield(self, **kwargs):
>     defaults = {'form_class': MultipleChoiceField,
> 'widget':CheckboxSelectMultiple, 'choices':map(lambda f: (f, f),
> self.flags)}
>     defaults.update(kwargs)
>     return super(FlagField, self).formfield(**defaults)
>
> Regards,
>
>
> --
> - Paul Kenjora
> - 602-214-7285
>
> --
> You received this message because you are subscribed to the Google Groups
> "Django developers" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to [email protected].
> To post to this group, send email to [email protected].
> Visit this group at http://groups.google.com/group/django-developers.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-developers/CAEH8JE3356WqGVgF9fNxYhTXs%2BVDNVm-iryTBCoFoB6bXcxOgA%40mail.gmail.com
> .
> For more options, visit https://groups.google.com/groups/opt_out.
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at http://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/CAGdCwBupWAWf1%2Bp%2BxJF7Ttq8EV%3DzDZPA689DCB9SF2G7HQCh2A%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to