来自多个对象的Django ForeignKey

时间:2012-02-13 00:56:16

标签: python django

我正在创建一个应用,用户可以订阅/关注网站的不同方面。

我正在构建将记录所有这些订阅的表。我最初的直觉是制作一个订阅表,它将列出订阅的所有内容。以下是我现在的计划:

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列将有一个外来对象。

这是有效的,但在逻辑中需要很多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

有关如何简化这一点的任何想法?或者这没关系?

1 个答案:

答案 0 :(得分:3)

您可以使用generic foreign keys(带有一个subscription_to字段)或model inheritance(具有Subscription的子类用于不同的订阅类型,这至少可以让您使用更好地构建代码。)