Tuesday, 2 August 2022

django model how to define unique key constraint

use meta class inside model class which will be called first

https://stackoverflow.com/questions/2201598/how-to-define-two-fields-unique-as-couple

 class Volume(models.Model):

    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
        ]

No comments:

Post a Comment