Hi,

How can I create a table with a fixed-length binary field with a unique
constraint?

I need to save a SHA-256 checksum as a part of my objects, and I need to make
sure I never have two or more objects with the same checksum in the database.
Also, I need to be able to look up objects by that checksum.

I have tried defining the model like this:

class Certificate(models.Model):
    ...
    fingerprint_sha256 = models.BinaryField(max_length2)
    class Meta:
        db_table="certificates"
    ...

Problems with this:

- BinaryField does not seem to support a length parameter, just max_length.

- When I make a migration with that model and apply it to a MySQL database,
the resulting field will be of type "longblob" instead of the "binary(32)" I
was going for.

- MySQL cannot create a unique constraint on a binary field without a length
constraint (or a length constraint over 255). If I add a unique=True parameter
to that field, migrating that change to a MySQL database will fail.

I can just manually connect to the MySQL server on the command line and change
the field to what I want, and in fact the Django app will work fine like that,
however I have a feeling that this undermines Django's database migration
concept and may lead to unforeseen problems in the future. (Also, I don't want
to unnecessarily complicate the install process for the app beyond what is
normal for a Django app.)

I could save the checksum as an ASCII representation in a CharField instead,
however this would more than double storage requirements for the field
(possibly even quadruple when using UTF-8 charset). This table is going to be
very large and very busy in production, and I'm afraid that any increase in
row size is going to be detrimental to performance.

Does anyone have a good idea how to solve this problem?

Regards,

        Guido

--
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/2450876.KIxDkREjN7%40nb-winkelmann.
For more options, visit https://groups.google.com/d/optout.

Attachment: smime.p7s
Description: S/MIME cryptographic signature

Reply via email to