如何创建主键由Django中的两个字段组成? [英] How to create a primary key consists of two fields in Django?

查看:1065
本文介绍了如何创建主键由Django中的两个字段组成?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个特定的应用程序,我发现使用指定的数据库和模型模式。我使用Django版本1.8.2。下面提出了一个问题。不必要的字段已被省略,模型名称是为了示例的目的而发明的,因为我不能公开。考虑以下模型A和B.

I develop a certain application, which I found with the specified database and model schema. I am using Django version 1.8.2. Below is presented a problem. Unnecessary fields have been omitted, model names are invented for the purposes of an example, because I can not disclose. Consider the following models A and B.

class B (models.Model):

      name = models.CharField(max_length=100)

class A (models.Model):

      name = models.CharField(max_length=100, primary_key=True)
      related_name = models.ForeignKey(B, null=True, blank=True)

项目可能存在几个相同的名字A,但具有不同的外键B.在这种特殊情况下,我想建模主键A,由两个字段组成:名称和相关名称。如何创建这样的键由django中的两个字段组成?

After a long time a project the possibility that there may be several of the same name A, but with different foreign key B. In this particular case, I would like to model the primary key "A" consisted of two fields: name and related name. How to create such a key consists of two fields in django?

推荐答案

要使用复合键。 Django不支持此请参阅此处

You want to use a composite key. Django does not support this See here. There is some support but you can't have relationships so it's pretty limited as far as practical usage.


目前,Django模型只支持一个单一的列,
拒绝许多设计,其中表的自然主键是
多列。 Django目前不能使用这些模式;他们
必须改为引入一个冗余的单列键(一个代理
键),迫使应用程序做任意和不必要的
选择关于哪个键用于表在任何给定实例。

Currently Django models only support a single column in this set, denying many designs where the natural primary key of a table is multiple columns. Django currently can't work with these schemas; they must instead introduce a redundant single-column key (a "surrogate" key), forcing applications to make arbitrary and otherwise-unnecessary choices about which key to use for the table in any given instance.

这篇关于如何创建主键由Django中的两个字段组成?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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