I have two tables. First is Users
table and second is Referrals
table. Referrals table looks like this:
| Referrals table columns | Points to
| ----------------------- | ---
| new_customer_id | user table's primary key
| referred_by | user table's primary key
The requirement is that if Person B (ID: 2) is referred by Person A (ID: 1), we should not be able to insert the other way around. In other words, the table should not have data like this:
| new_customer_id | referred_by |
| --------------- | ----------- |
| 2 | 1 | <-- OK
| 1 | 2 | <-- Both people refering each other should not be allowed
Is it possible to check this during insert on database level. I'm using mysql. I read a bit about mysql CHECK constraint here, but cannot figure out how to implement this.
I'm using django ORM and here is what I have tried but failed.
class Referrals(models.Model):
customer = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, db_index=True)
referred_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, db_index=True)
class Meta:
constraints = [
models.CheckConstraint(check=models.Q(customer__gt=models.F('referred_by')),
name='referrer_should_come_before_referee')
]
If it is not possible with Django ORM but possible in database level with some query, that's fine also. However, +1 for django solution. :)
Thank you.