简体   繁体   中英

Django: Make a column which is not primary key unique

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, ie 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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM