unique together

Date: March 25th 2016
Last updated: March 25th 2016

unique_together is an option that can be added to a model in models.py. unique_together is executed at the database-level so it requires a suitable backend to work. I have tried it with MySQL and it works. The main premise is to pass a tuple of tuples containing the fields that must be unique in the table (model).

In this example I wanted to restrict a database table containing surfboards from receiving duplicate entries. Only the major differences are distinguished.

models.py

class Board(models.Model):
    SQUASH = 'SQH'
    SQUARE = 'SQE'
    ROUNDED = 'ROU'
    TAIL = ((SQUASH, 'Squash'),
            (SQUARE, 'Square'),
            (ROUNDED, 'Rounded'),
    #<- snipped ->
    boardtail = models.CharField('Tail shape', max_length=3, choices=TAIL)
    boardlength = models.DecimalField('Length', max_digits=4, decimal_places=2)
    boardwidth = models.DecimalField('Width', max_digits=4,
                  decimal_places=2, null=True, blank=True)
    boardmake = models.CharField('Make', max_length=20)
    #<- snipped ->

    def __str__(self):
        return '{} {}'.format(self.boardlength, self.boardmake)

    ###################### solution ########################
    # Note that this failed when passing only one set of tuples
    class Meta:
        unique_together = (('boardtail', 'boardlength', 
                            'boardmake', 'boardwidth'))
    ########################################################

http://127.0.0.1:8080/1/boards/

results matching ""

    No results matching ""