title = models.CharField(max_length=200)
ISBN = models.CharField(max_length=50,primary_key=True)
author = models.CharField(max_length=80)
press = models.CharField(max_length=100)
category = models.CharField(max_length=30,primary_key=True)
series = models.CharField(max_length=50,null=True)
class Meta:
unique_together = ('ISBN','category')
需要实现 ISBN+category 唯一,但是我发现插入第二条就报错了
2017-12-01 22:05:04] [19] [SQLITE_CONSTRAINT_PRIMARYKEY] A PRIMARY KEY constraint failed (UNIQUE constraint failed: coding_book.category)
是我这样写不对吗,望各位指教。需要怎么写?
1
yaoht 2017-12-01 22:27:07 +08:00
ISBN = models.CharField(max_length=50,primary_key=True)
category = models.CharField(max_length=30,primary_key=True) 这两个都有 primary_key=True, 也就是说他们各自都必须 unique 并不是你想要的 MultipleColumnPrimaryKeys https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys |
2
gaolycn 2017-12-02 01:57:16 +08:00 via Android
unique_together = (('ISBN','category'),)
|
3
jimzhong 2017-12-02 12:39:20 +08:00
Django 尚未支持复合主键,https://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys
我会使用 Django 自动创建的 id 主键,然后加上 unique 约束: ```python title = models.CharField(max_length=200) ISBN = models.CharField(max_length=50) author = models.CharField(max_length=80) press = models.CharField(max_length=100) category = models.CharField(max_length=30) series = models.CharField(max_length=50,null=True) class Meta: unique_together = ('ISBN','category') ``` @gaolycn 并不需要这么写,https://docs.djangoproject.com/en/1.11/ref/models/options/#unique-together |