Django UniqueConstraint error on a foreign key relationship

I'm really stuck on this issue.

I need to import in my django web app an existing database. I got problem on setting the foreign relationship between IrmaTblcardpoc and IrmaTblcardstreet knowing that mykey and streetid are the "composite keys".

I got the following error:

myapp.IrmaTblcardpoc.street: (fields.E311) 'IrmaTblcardstreet.streetid' must be unique because it is referenced by a foreign key.

This is a bit above my paygrage unfortunately. What am i doing wrong?

class IrmaTblunit(models.Model):
    mykey = models.CharField(db_column='myKey', primary_key=True, max_length=50)

    def __str__(self):
        return self.id
#...
class IrmaTblcardstreet(models.Model):
    mykey =  models.ForeignKey(IrmaTblunit, on_delete=models.CASCADE)
    streetid = models.CharField(db_column='StreetID', max_length=100)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['mykey', 'streetid'], name='unique_mykey_streetid')
        ]

    def __str__(self):
        return self.mykey + self.streetid

class IrmaTblcardpoc(models.Model):
    mykey =  models.ForeignKey(IrmaTblunit, on_delete=models.CASCADE, related_name='children')
    pocid = models.CharField(db_column='POCID', max_length=100, blank=True, null=True)  
    cardid = models.BigIntegerField(db_column='CardID', blank=True, null=True)
    streetid = models.ForeignKey(IrmaTblcardstreet, on_delete=models.CASCADE, to_field='streetid', db_column='streetid', related_name='poc_streets'

    class Meta:
        db_table = 'irma_tblCardPOC'
        constraints = [
            models.UniqueConstraint(fields=['mykey', 'streetid', 'pocid'], name='unique_mykey_pocid')
        ]

    def __str__(self):
        return self.mykey + self.pocid

class IrmaTblcardstreet(models.Model):
    ...
    streetid = models.CharField(db_column='StreetID', max_length=100)


class IrmaTblcardpoc(models.Model):
    ...
    streetid = models.ForeignKey(IrmaTblcardstreet, on_delete=models.CASCADE, to_field='streetid', db_column='streetid', related_name='poc_streets'

You are trying to add foreign key that is not-unique field. If you need to connect these models use to_field='pk' and delete db_column or even do not use this keyword, - Django will automatically bind these models under the hood with AutoField pk

Back to Top