I'm working on a Django/Python API project and I need one of my models to have a unique_together combination along with a given condition on another field of the model.
Ex:
user | date |from_time | to_time | status
====================================================
1 | 2020/01/01 |10 am | 12 pm | Active
1 | 2020/01/01 |10 am | 12 pm | Inactive
1 | 2020/01/01 |9 am | 12 pm | Inactive
1 | 2020/01/01 |12 pm | 3 pm | Active
----------------------------------------------------
2 | 2020/01/01 |9 am | 3 pm | Active
2 | 2020/01/01 |10 am | 3 pm | Inactive
unique_together = [['user', 'date', 'from_time'], ['user', 'date', 'to_time']]
This unique combination only allows to save only one record that validates this combination. Adding "status" field to this unique combination will allow adding overlapping times with the same status. So in my application I need to have only one record following the above unique_together combination when its status is "Active" and multiple if it's "Inactive" as shown in the example data set above.
Removing the above unique_together combination to UniqueConstraint also fails producing an error in the console upon migrating.
constraints = [
models.UniqueConstraint(fields=['user', 'date', 'from_time'], condition=Q(status='Active'), name='uc_user_date_from_active'),
models.UniqueConstraint(fields=['user', 'date', 'to_time'], condition=Q(status='Active'), name='uc_user_date_to_active')
]
Error
django.core.exceptions.FieldError: Joined field references are not permitted in this query
How can I get this validation done in the Model itself without having to manually validate?