Johan Hjalmarsson
Johan Hjalmarsson

Reputation: 3493

unique column value per row

I find it best to use an example, so here we go:

Say I have a table with chores and a table with a weekly schedule like this:

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

I want to make sure that for one week, you can't have duplicate cells, so this wouldn't be allowed:

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

etc

What would I have to do in my models.py to get this behaviour?

Upvotes: 0

Views: 40

Answers (2)

vZ10
vZ10

Reputation: 2686

I'd better user ManyToMany through another table like that:

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

And trough table like that

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

And in that table make unique together for week_id and chores_id

Upvotes: 1

Neeraj Kumar
Neeraj Kumar

Reputation: 3951

Try django unique-together in model meta option. https://docs.djangoproject.com/en/1.11/ref/models/options/#unique-together

Upvotes: 1

Related Questions