[Django]-Unique_together and M2M field

3👍

you can use through in ManyToManyFieldand connect your many to many relations through custom intermediate table. then add unique_together there:

class CodeSynonyms(models.Model):
    # add through field
    websites = models.ManyToManyField(Websites, through='WebsiteCode')
    synonym = models.Charfield(max_length=10)

class WebsiteCode(models.Model):
    code_synonym = models.ForeignKey(CodeSynonyms, on_delete=models.CASCADE)
    website = models.ForeignKey(Websites, on_delete=models.CASCADE)
    code = models.ForeignKey(Codes, on_delete=models.CASCADE)

    class Meta:
        unique together = ('code', 'website')

Leave a comment