Question

I have a list of numeric codes with corresponding mnemonic names and I want to have a Django model for them so the names are primary keys, but there is also a constraint that the values in the code column are unique.

What I tried is the following:

class Constant(models.Model):
    name = models.CharField(max_length=70)
    name.primary_key = True
    code = models.IntegerField()
    description = models.CharField(max_length=100)

    unique_together = (("code",),)

I realize that unique_together is meant to enforce uniqueness of values in a set of columns, but I thought I would try with just one and it seemed to work, i.e. no error when doing python manage.py syncdb, but it doesn't really enforce the constraint I want:

mysql> describe constant;
+-------------+--------------+------+-----+---------+-------+
| Field       | Type         | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+-------+
| name        | varchar(70)  | NO   | PRI |         |       |
| code        | int(11)      | NO   |     |         |       |
| description | varchar(100) | NO   |     |         |       |
+-------------+--------------+------+-----+---------+-------+
3 rows in set (0.01 sec)

mysql> insert into constant values ('x',1,'fooo');
Query OK, 1 row affected (0.00 sec)

mysql> insert into constant values ('y',1,'foooo');
Query OK, 1 row affected (0.00 sec)

What can I do to make sure values in both columns are unique?

Was it helpful?

Solution

Add the unique option to your code field.

class Constant(models.Model):
    name = models.CharField(max_length=70, primary_key=True)
    code = models.IntegerField(unique=True)
    description = models.CharField(max_length=100)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top