Django 反序列化器,字段设置为serialize=False
[编辑:使用 django-1.1.1]
你好,
我正在使用 django 类来存储与对象图标相对应的 blob(更准确地说是 b64 编码的字符串)。
我将对象序列化为 json 以与不同的前端客户端进行通信。
我不想在 json 结果中公开纯图标 blob(而是将其作为某个 url 下的图像),因此我的图标字段定义如下:
icon = models.TextField(null=True, serialize=False)
但是当需要保存我的对象时,我丢失了我的图标,因为,显然,该值不是由传入的 json 字典设置的。
我想写一个像这样的黑客:
class MyIconizedClass(models.Model):
def __init__(self, *args, **kwargs):
if self.pk is not None and self._icon is None:
old_self = MyIconizedClass.object.get(pk=self.pk)
self.icon = old.self.icon
对此不太满意,因为它每次都会在数据库中查询,另外,如果图标实际上是“无”,它将无限期地递归。
另一种方法是重写解串器。
有没有使用 django 内部机制的解决方法?
[edit: using django-1.1.1]
Hello,
I'm using django classes that store a blob (a string b64 encoded more exactly) corresponding to an icon for the object.
I serialize the objects as json to communicate with the different front-end clients.
I don't want to expose the pure icon blob in the json result (but serve it as image under a certain url), so my icon field is defined as thus :
icon = models.TextField(null=True, serialize=False)
But when time comes to save my object, I lose my icon, because, obviously, the value is not set by the incoming json dictionnary.
I'd like to write written a hack like so :
class MyIconizedClass(models.Model):
def __init__(self, *args, **kwargs):
if self.pk is not None and self._icon is None:
old_self = MyIconizedClass.object.get(pk=self.pk)
self.icon = old.self.icon
Not very satisfied with this because it would query in DB every time, plus, it will recurse indefinitely if the icon is effectively None.
Another way would be to rewrite the deserializer.
Is there any workaround, using django's internal mechanisms?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个:
它也会查询数据库,但不会导致任何递归。
Try this:
It also queries the database but it won't cause any recursion.
我改变了我的模型,以减少查询贪婪。
我只按需查询 IconClass 表,当使用某些 url 入口点时,例如
当访问对象本身时,我不需要了解图标(GET /iconized/42)。
I changed my model so as to be less query-greedy.
I only query the IconClass table on demand, when working with certain url entrypoints such as
When accessing the object itself, I don't need to know of icons (GET /iconized/42).