Reputation: 83
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?
Upvotes: 0
Views: 2246
Reputation: 430
As of July 29, 2024, work to add composite primary keys is still ongoing. The original pull request below appears to have stagnated, with development being moved to a new pull request which was started in April 2024, based on the original pull request. As far as I can tell, all work for adding composite primary keys/composite foreign keys is now being handled from this newer pull request.
In contrast to the currently-accepted answer from 2020, it appears that as of September 2023, there is ongoing work to finally implement composite primary keys/foreign keys. If I understood the PR's discussion correctly, then they've already got composite primary keys working, but need to make it work with foreign keys as well before they can actually merge the changes.
See this PR for details: https://github.com/django/django/pull/17279
Upvotes: 2
Reputation: 15738
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
Upvotes: 2