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

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

问题描述

我有一个这样的模型:

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



解决方案

我会实现这一点。

>

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

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

class Meta:
unique_together =((migration,host))
/ pre>

它将作为代理主键列。



如果您真的要创建多列主键,请查看这个应用程序


I have a model like this:

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 primary key.

解决方案

I would implement this slightly differently.

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天全站免登陆