Django unique_together model by primary key and unique constraints

I have a model 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 wrote ap = '1', de = '2' in the mc table.

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

Then I tried to write ap = '1' and de = '3', but he 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 gave unique_together, the combination of ap and de does not work.

But unique_together works if I did not use the "primary_key" or "unique" constraints for either ap or de.

Could you help me? How to use unique_together on primary keys?

The actual problem is that I have another class mc1 that uses a foreign key for the ap field.

class mc1(models.Model):                                                                                            

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

, mc.ap .

+4
1

Django . . .

, ap , ap . (ap=1, de=2), (ap=1, de=3).

, . unique_together ('ap', 'de').

+6

Source: https://habr.com/ru/post/1680780/


All Articles