[英]Django + Postgres: A string literal cannot contain NUL (0x00) characters
I'm syncing a large amount of data and I'm getting this error back: A string literal cannot contain NUL (0x00) characters.
我正在同步大量数据,但出现此错误:
A string literal cannot contain NUL (0x00) characters.
Obviously this is a postgres problem, but I'm not quite sure how to solve it.显然这是一个 postgres 问题,但我不太确定如何解决它。 Is there a way to strip null characters out at the Django model level?
有没有办法在 Django 模型级别去除空字符? I have a large set of fields that I'm syncing.
我有一大堆要同步的字段。
This bug fix suggests:此错误修复建议:
s.decode("utf-8", errors="replace").replace("\x00", "\uFFFD")
Only the .replace
is necessary for the OP's issue, which replaces the null with a character.对于 OP 的问题,只有
.replace
是必需的,它将用 字符替换空值。 I've included .decode
too as it protects against other encoding issues that might arise in similar situations.我也包含了
.decode
因为它可以防止在类似情况下可能出现的其他编码问题。
This would go in a .clean
method somewhere - maybe subclass TextField or CharField if you want to apply it globally.这将在某处使用
.clean
方法 - 如果您想全局应用它,可能是 TextField 或 CharField 的子类。
Unless you definitely do want to store NUL characters, you should sanitize your text so it does not contain them.除非您确实想要存储 NUL 字符,否则您应该清理您的文本,使其不包含它们。 At the model level, you'd define a
clean_fieldname
method to do that.在模型级别,您将定义一个
clean_fieldname
方法来执行此操作。
If you do want to store them, you need to store them in a binary-compatible field in the database.如果确实要存储它们,则需要将它们存储在数据库中的二进制兼容字段中。 Django 1.6+ has
BinaryField
which should work. Django 1.6+ 有
BinaryField
应该可以工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.