Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set BinaryField to primary key in django?

Tags:

django

binary

In this code i have:

IDChuyenBien = models.BinaryField(primary_key=True, max_length=8)

But when i makemigrations and migrate have an error:

    _mysql.connection.query(self, query)
django.db.utils.OperationalError: (1170, "BLOB/TEXT column 'IDChuyenBien' used in key specification without a key length")

Although I used max_length as above, I am using Django 4.2.9 connect to Mysql.

I followed the docs as follows: https://docs.djangoproject.com/en/4.2/ref/models/fields/
I have also tried to think of a few other ways but still do not have a solution, because it is required that the data transmitted is binary and will be saved directly to the database, and before that when I did not use the primary key, in mysql when migrating it was also LONGBLOB. Meanwhile t only needs BINARY type with 8 bytes or 10 bytes

like image 936
couz2200 Avatar asked Jan 20 '26 12:01

couz2200


1 Answers

TLDR: at the moment of writing, you can not set a BinaryField as a primary key.

Django does not take the length of the field to the SQL database, it is only used to validate items internally. This thus means that for MySQL, it will use a longblob, for Oracle a BLOB, for PostgreSQL a bytea and for SQLite a BLOB. Indeed, as we see for example for MySQL [GitHub]:

"BinaryField": "longblob",
"BooleanField": "bool",
"CharField": "varchar(%(max_length)s)",

So in this case, a BinaryField translates to a longblob in MySQL, whereas for a CharField, it picks varchar(…), but specifies the length.

This is thus not passed to the database backend, and therefore you can not use the field as a primary key, since only for small blobs, it does the effort of hashing.

That being said, it is probably not a good idea to use a BinaryField in the first place. In fact, in Django an using an AutoField is the norm, and one can then use for example GenericForeignKey fields [Django-doc] that exploits the fact that primary keys are uniform.

like image 110
Willem Van Onsem Avatar answered Jan 22 '26 08:01

Willem Van Onsem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!