Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a primary key consists of two fields in Django?

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)

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?

like image 653
sweet_sugar Avatar asked Jul 09 '15 18:07

sweet_sugar


1 Answers

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.

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.

like image 149
mikeb Avatar answered Oct 07 '22 02:10

mikeb