Django model unique_together on primary key and unique constraints

Viewed 5549

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.

1 Answers
Related