I want to satisfy this relationship in a Django SQLite DB (ER Diagram), I have tried using both the unique_together
and models.UniqueConstraint
solutions that I've seen suggested.
myapp/models.py
class User(models.Model):
user_id = models.AutoField(primary_key=True, null=False)
class Article(models.Model):
article_id = models.AutoField(primary_key=True)
class ArticleEditor(models.Model):
class Meta:
# RECOMMENDED
models.UniqueConstraint(fields=['article_id', 'editor_id'], name="article_editor_id",)
# DEPRECATED
unique_together = (('article_id', 'editor_id'),)
article_id = models.ForeignKey(
Article,
on_delete=models.CASCADE,
)
editor_id = models.ForeignKey(
User,
on_delete=models.PROTECT,
)
In both cases, when I try saving an ArticleEdiotor object through the python console, I get this error:
>>> from myapp.models import User, Article, ArticleEditor
>>> a = Article.objects.get(article_id=2)
>>> u = User.objects.get(user_id=1)
>>> ae = ArticleEditor(a.article_id, u.user_id)
>>> ae.save()
Traceback (most recent call last):
...
django.db.utils.OperationalError: no such table: myapp_articleeditor
However, I checked the sqlmigrate
command for the migration and it does CREATE TABLE "myapp_articleeditor"
; but it still makes an "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT
that I don't want, as I'd like for my composite key (article_editor_id
) to be the primary key. How to I achieve this?
And is this actually the best way to make a many-to-many relationship that has an intermediate table, like depicted in the diagram, or is there a better solution?
Django does not support multi-column primary key, unique together is proposed workaround but you will still have one column to act as real id
There is no work being done on this topic for long time Wiki article, django-compositepks