views:

509

answers:

3

I have a twenty byte hex hash that I would like to store in a django model. If I use a text field, it's interpreted as unicode and it comes back garbled.

Currently I'm encoding it and decoding it, which really clutters up the code, because I have to be able to filter by it.

def get_changeset(self):
    return bin(self._changeset)

def set_changeset(self, value):
    self._changeset = hex(value)

changeset = property(get_changeset, set_changeset)

Here's an example for filtering

Change.objects.get(_changeset=hex(ctx.node()))

This is the approach that was recommended by a django developer, but I'm really struggling to come to terms with the fact that it's this ugly to just store twenty bytes.

Maybe I'm too much of a purist, but ideally I would be able to write

Change.objects.get(changeset=ctx.node())

The properties allow me to write:

change.changeset = ctx.node()

So that's as good as I can ask.

+1  A: 

I'm assuming if you were writing raw SQL you'd be using a Postgres bytea or a MySQL VARBINARY. There's a ticket with a patch (marked "needs testing") that purportedly makes a field like this (Ticket 2417: Support for binary type fields (aka: bytea in postgres and VARBINARY in mysql)).

Otherwise, you could probably try your hand at writing a custom field type.

Yoni Samlan
+2  A: 

You could also write your own custom Model Manager that does the escaping and unescaping for you.

Sam Corder
+2  A: 

"I have a twenty byte hex hash that I would like to store in a django model."

Django does this. They use hex digests, which are -- technically -- strings. Not bytes.

Do not use someHash.digest() -- you get bytes, which you cannot easily store.

Use someHash.hexdigest() -- you get a string, which you can easily store.

Edit -- The code is nearly identical.

See http://docs.python.org/library/hashlib.html

S.Lott
Using a different encoding doesn't make the code any cleaner. If I still have to encode and decode I haven't gained anything.
mbarkhau
Sorry if my answer confused you. I've revised it. digest() and hexdigest() are nearly identical. Except you can persist hexdigest(). You can't easily persist digest().
S.Lott