在Django模型字段中存储二进制哈希值 [英] Storing a binary hash value in a Django model field

查看:315
本文介绍了在Django模型字段中存储二进制哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个二十字节的十六进制哈希,我想存储在一个django模型。
如果我使用一个文本字段,它被解释为unicode并且它回来乱码。



目前我正在对它进行编码并对其进行解码,因为我必须能够通过它进行过滤

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

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

changinget = property(get_changeset,set_changeset)

这是一个过滤

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

这是django开发人员推荐的方法,但是真的很难想到这个事实,只是存储二十个字节这是丑的。



也许我太纯粹,但理想情况我会可以写

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

属性允许我写:

  change.changeset = ctx.node()

这样就好像我可以问。

解决方案

如果您正在编写原始SQL,那么您将使用Postgres bytea或MySQL VARBINARY。有一个带有补丁的机票(标有需要测试),据称这样做了一个字段(票2417:支持二进制类型字段(又名:postgres中的bytea和mysql中的VARBINARY))。



否则,您可能会在撰写自定义字段类型


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.

解决方案

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.

这篇关于在Django模型字段中存储二进制哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆