每行唯一列值

时间:2017-06-04 22:15:41

标签: django django-models

我觉得最好用一个例子,所以我们走了:

假设我有一张带家务的桌子和一张每周安排的表格如下:

CHORES:
|----+---------------+----------+-------|
| id |      name     |   type   | hours |
|----+---------------+----------+-------|
| 1  | clean kitchen | cleaning |   4   |
|----+---------------+----------+-------|
| 2  | clean toilet  | cleaning |   3   |
etc

SCHEDULE:
|------+---------------+---------------+-----|
| week |     monday    |    tuesday    | etc |
|------+---------------+---------------+-----|
|   1  | clean kitchen | clean toilet  | etc |
|------+---------------+---------------+-----|
|   2  | clean toilet  | clean kitchen | etc |
etc

我想确保一周内你不能有重复的单元格,所以不允许这样做:

SCHEDULE:
|------+---------------+--------------+-----|
| week |     monday    |   tuesday    | etc |
|------+---------------+--------------+-----|
|   1  | clean toilet  | clean toilet | etc |

etc

我需要在models.py中做些什么才能得到这种行为?

2 个答案:

答案 0 :(得分:1)

在模型元选项中尝试django unique-together。 https://docs.djangoproject.com/en/1.11/ref/models/options/#unique-together

答案 1 :(得分:1)

我最好通过另一个表格来使用ManyToMany:

SCHEDULE:
 ------+------------------------+
| week |     chores             |    
|------+------------------------+
|   1  | many to many to chores |
|------+------------------------+
|   2  | many to many to chores |

和那样的表格

THROUGH TABLE:
|---------+---------------+---------------+
| week_id |  day of week  |    chores_id  |
|---------+---------------+---------------+
|   1     | Monday        | clean toilet  |
|---------+---------------+---------------+
|   1     | Tuesday       | clean kitchen |

并且在该表中为week_id和chores_id

制作唯一