简体   繁体   English

Django + Postgres:字符串文字不能包含 NUL (0x00) 字符

[英]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.

相关问题 Django URL arg不能包含NUL(0x00)字符 - Django url arg cannot contain NUL (0x00) characters Django + Postgres:将带有 NUL (0x00) 字符的 PDF 文件保存到 DB 并将其解码回 PDF - Django + Postgres: saving PDF file with NUL (0x00) characters to DB and decoding it back to PDF 带字节的串行通信(0x00 问题) - Serial communication with bytes (0x00 problem) <read-write buffer ptr 0x00, size 855 at 0x00>蟒蛇 - <read-write buffer ptr 0x00, size 855 at 0x00> python Python 将十六进制值从 0x00 转换为 0x0 - Python convert hex value from 0x00 to 0x0 如何将包含 NUL 行 (&#39;\\x00&#39;) 的 csv 读入熊猫? - How to read a csv with rows of NUL, ('\x00'), into pandas? 将0x20、0x00、0x0d,0x0a字节传递给strcmp() - Passing 0x20, 0x00, 0x0d, 0x0a bytes to strcmp() Python-对于每个读入的十六进制字节,使用0x00重写字节数组 - Python - rewrite byte array with 0x00 for each hex byte read in PostgreSQL - Psycopg2 - copy_from - 用于编码“UTF8”的无效字节序列:0x00 - PostgreSQL - Psycopg2 - copy_from - Invalid byte sequence for encoding “UTF8”: 0x00 使用Python GEDCOM解析器:接收到错误的输出(gedcom.Element实例位于0x00…) - Using a Python GEDCOM parser: Receiving bad output (gedcom.Element instance at 0x00…)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM