私はユーザーがサイトのさまざまな側面を購読/追跡できるアプリケーションを作成しています。複数のオブジェクトからのDjango ForeignKey
これらのサブスクリプションをすべて記録するテーブルを作成しています。私の最初の本能は、サブスクリプションテーブルを作成することです。ここで私は今それを計画しています方法です:
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)
これは動作するはずですが、それはこれを行うための最も効率的な方法だ場合、私は思ったんだけど。各行にはサブスクライバIDと型選択があり、それに応じてsubscription_to列の1つに異種オブジェクトがあります。
これは動作していますが、ロジックには多くのif/elseステートメントが必要です。たとえば、
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
これを簡略化する方法についてのご意見はありますか?またはこれは大丈夫ですか?