9

I want to use UUIDs for database ids instead of autoincrement integers. I understand that this can be done by overriding the id in the Model class, for example:

from django.db import models

class Publication(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    title = models.CharField(max_length=30)

class Article(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication)

But, there is still a problem. The automatically generated table for the ManyToMany field uses an auto-incremented id, not a UUID.

Of course, this can address this by defining a "through" table as follows:

...
class Article(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    headline = models.CharField(max_length=100)
    publications = models.ManyToManyField(Publication, through="ArticlePublication")

class ArticlePublication(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    publication = models.ForeignKey(Publication, on_delete=models.CASCADE)

But, according to the Django docs, when you use a "through" table: "Unlike normal many-to-many fields, you can’t use add(), create(), or set() to create relationships". Also, not "DRY".

I want to use add, create and set , and I like the "DRY" feature of the ManyToMany field. I also want to use UUIDs as ids.

I looked for a parameter to ManyToMany to pass in the definition of the automatically created "id" field, but there isn't one.

Am I missing something, or is this a limitation of Django's support for UUID as primary key?

EMS
  • 1,033
  • 1
  • 9
  • 11

0 Answers0