简体   繁体   English

来自外键的 Django 复合主键的最佳解决方案

[英]best solution for Django Composite primary-key from foreign-keys

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.我想在 Django SQLite DB( ER 图)中满足这种关系,我尝试过使用我所建议的unique_togethermodels.UniqueConstraint解决方案。

myapp/models.py 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:在这两种情况下,当我尝试通过 python 控制台保存 ArticleEdiotor object 时,都会收到以下错误:

>>> 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" ;但是,我检查了迁移的sqlmigrate命令,它确实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.但它仍然使我不想要一个"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT ,因为我希望我的复合键( article_editor_id )成为主键。 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 Django 不支持多列主键,建议使用唯一的解决方法,但您仍将有一列用作真实 ID

There is no work being done on this topic for long time Wiki article , django-compositepks长时间Wiki 文章django-compositepks没有关于此主题的工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM