如何在Django中为我的模型设置两个主键字段 [英] How can set two primary key fields for my models in Django

查看:366
本文介绍了如何在Django中为我的模型设置两个主键字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的模型:

class Hop(models.Model):
    migration = models.ForeignKey('Migration')
    host = models.ForeignKey(User, related_name='host_set')

我要迁移并同时将它们托管在一起作为主键.

I want to migration and host both together be the primary key.

推荐答案

我会稍微不同地实现这一点.

I would implement this slightly differently.

我将使用默认的主键(自动字段),并使用元类属性unique_together

I would use a default primary key (auto field), and use the meta class property, unique_together

class Hop(models.Model):
    migration = models.ForeignKey('Migration')
    host = models.ForeignKey(User, related_name='host_set')

    class Meta:
        unique_together = (("migration", "host"),)

它将充当代理"主键列.

It would act as a "surrogate" primary key column.

如果您确实要创建多列主键,请查看此应用

If you really want to create a multi-column primary key, look into this app

这篇关于如何在Django中为我的模型设置两个主键字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆