Reputation: 18428
I'm trying to create a simple model to keep track of discount coupons in Django 1.10 (with Postgres 9.5 as underlying database) and I was wondering if there's a way to make sure that a coupon instance (id
, perhaps is a more accurate term?) doesn't appear in two M2M relationships at the same time.
I'm sure everyone is familiar with how discount coupons work but, just in case, let me explain my use case:
To keep track of those things, I have a model like this:
class CouponTracker(models.Model):
# Coupons that require a code to be activated:
extra_applied_coupons = ManyToManyField('Coupon', related_name='+')
# Coupons that the user could have applied and specifically
# said no (such as 5% off if the purchase is small, and wants
# to use it later):
vetoed_coupons = ManyToManyField('Coupon', related_name='+')
So, the question is:
How can I enforce (at a database level, through a constraint) that a coupon does not appear at the same time in extra_applied_coupons
and vetoed_coupons
?
Thank you in advance!
Upvotes: 1
Views: 1265
Reputation: 22403
Why don't you combine 2 extra_applied_coupons
and vetoed_coupons
and have 1 more fields (for example, type
) to determine coupon's group. Then problem will be simpler, just ensure unique in 1 ManyToMany
relationship
class CouponTracker(models.Model):
coupons = ManyToManyField('Coupon', related_name='+')
type = models.IntegerField(default=0)
type
can be 0 for extra_applied_coupons
and 1 for vetoed_coupons
.
If you want to add more relationship attribute, you can check https://docs.djangoproject.com/en/1.11/topics/db/models/#extra-fields-on-many-to-many-relationships
Upvotes: 2