[Fixed]-Unique field in Django Model for each foreign key

33👍

You can use unique together in your model is meta:

class Chapter(models.Model):
    doc = models.ForeignKey('Document')
    chapter = models.IntegerField()

    class Meta:
        unique_together = (("doc", "chapter"),)  

Here’s the doc

(Django 3.1) edit: Using unique_together is now discouraged by the docs and may be deprecated in the future, as per the docs. Use UniqueConstraint instead:

class Chapter(models.Model):
    doc = models.ForeignKey('Document')
    chapter = models.IntegerField()

    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=['doc', 'chapter'], 
                name='unique chapter'
            )
        ]
👤Mounir

Leave a comment