I am creating an application in which the user can subscribe / follow various aspects of the site.
I am creating a table in which all these subscriptions will be written. My initial instinct is to make one subscription table that lists everything that is subscribed to. Here is how I plan now:
class SubscriptionTypeCode(object): CITY = '1' REGION = '2' COUNTRY = '3' USER = '4' SUBSCRIPTION_TYPE_CHOICES = ( (SubscriptionTypeCode.CITY, 'City'), (SubscriptionTypeCode.REGION, 'Region'), (SubscriptionTypeCode.COUNTRY, 'Country'), (SubscriptionTypeCode.USER, 'User'), ) class Subscription(models.Model): subscriber = models.ForeignKey(User, related_name="subscriber") subscription_type = models.CharField(max_length=4, choices=SUBSCRIPTION_TYPE_CHOICES) subscription_to_user = models.ForeignKey(User, related_name="subscription_to_user", null=True, blank=True) subscription_to_city = models.ForeignKey(City, null=True, blank=True) subscription_to_country = models.ForeignKey(Country, null=True, blank=True) subscription_to_region = models.ForeignKey(Region, null=True, blank=True) created = models.DateTimeField(db_index=True, auto_now_add=True) cancelled = models.DateTimeField(null=True, blank=True)
This should work, but I wonder if this is the most efficient way to do this. Each row will have a subscriber identifier, then a type selection, and then, depending on this, one of the subscription_to columns will have a foreign object.
This works, but a lot of if / else statements are required in the logic. for instance
def create_subscription(request, subscription_type, subscription_id): subscription = Subscription.create( subscriber = request.user, subscription_type = subscription_type, ) if subscription_type == SubscriptionTypeCode.REGION: region = get_region(subscription_id) subscription.subscription_to_region = region elif subscription_type == SubscriptionTypeCode.CITY: city = get_city(subscription_id) subscription.subscription_to_city = city elif subscription_type == SubscriptionTypeCode.COUNTRY: country = get_country(subscription_id) subscription.subscription_to_country = country elif subscription_type == SubscriptionTypeCode.USER: user = get_user(subscription_id) subscription.subscription_to_user = user subscription.save() return subscription
Any thoughts on how to simplify this? Or is this normal?