Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django model unique_together on primary key and unique constraints

I have a model given below.

class mc(models.Model):
    ap=models.CharField(max_length=50,primary_key=True)
    de=models.CharField(max_length=50)
    STATUS=models.CharField(max_length=12,default='Y')
    class Meta:
        unique_together=(("ap","de"),)
        db_table='mc'

I have written ap='1', de='2' to table mc.

+----+----+--------+
| ap | de | STATUS |
+----+----+--------+
| 1  | 2  | Y      |
+----+----+--------+

Then i have tried to write ap='1' and de='3' but its just overwritten the previous one. Now the table contains

+----+----+--------+
| ap | de | STATUS |
+----+----+--------+
| 1  | 3  | Y      |
+----+----+--------+

Then i tried to write ap='2',de='3' and its work. Since i have given unique_together, the compination of ap and de is not working.

But unique_together work if i haven't used 'primary_key' or 'unique' constraints on either of ap or de.

Will you please help me.? How to use unique_together on primary keys?

Actual problem is that ,i have another class mc1 which use a foreign key to the field ap.

class mc1(models.Model):                                                                                            

    test=models.ForeignKey(mc,on_delete=models.CASCADE,to_field='ap')

So mc.ap should be unique to define a foreignkey.

like image 672
vishnu m c Avatar asked Jul 05 '17 08:07

vishnu m c


1 Answers

Django does not support multiple-column primary keys. It has been a feature request for several years. Each model must have one primary key.

In your case, if ap is the primary key, then each value in ap must be unique. It is not possible to store both (ap=1, de=2) and (ap=1, de=3).

Perhaps you could add another field as the primary key. Then you will be able to have unique_together for ('ap', 'de').

like image 104
Alasdair Avatar answered Oct 19 '22 23:10

Alasdair