Django 的复合/复合主/唯一键

发布于 2024-08-21 11:22:55 字数 43 浏览 13 评论 0原文

如何使用 Django 创建具有复合(复合)主/唯一键的模型(以及表)?

How can you create models (and thus tables) with a compound (composite) primary/unique key using Django?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

流年已逝 2024-08-28 11:22:55

Django 不支持复合主键。您可以使用 Meta 创建单个复合唯一键。 unique_together

Django does not support compound primary keys. You can create a single compound unique key with Meta.unique_together.

戏舞 2024-08-28 11:22:55

如果您只想将唯一的混合字段放在一起,请使用下面的代码:

class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField()
    key2 = models.IntegerField()

但是如果您希望将唯一的混合字段放在一起并且其中一列是主要的,请为模型列设置 primary 参数,类似于以下代码:

class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField(primary_key=True)
    key2 = models.IntegerField()

if you want only unique mixed fields together use belowcode:

class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField()
    key2 = models.IntegerField()

But if you want unique together and one of column be primary, set primary argument for model column, similar below code:

class MyTable(models.Model):
    class Meta:
        unique_together = (('key1', 'key2'),)

    key1 = models.IntegerField(primary_key=True)
    key2 = models.IntegerField()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文