获取通用外键的属性

时间:2015-10-13 00:26:19

标签: django generics django-contenttypes

我仍然试图将我的脑袋包裹在Django中的通用外键中,所以到目前为止我提出的是非常基本的。我正在尝试创建一个NotificationRecipient,它有一个我已经创建的2个不同模型的通用外键。这些通知收件人可以是ClientAccount。我可能决定添加更多新模型的收件人。

我想在NotificationRecipient中创建一个get_email方法,检查收件人是联系人,客户还是帐户。然后根据它的模型,它会提取不同的属性。

我现有的模型看起来有点像这样:

class Client(models.Model):
    primary_email = models.EmailField(blank=True)
    ...

class Account(AbstractNamedUser):
    email = models.EmailField(blank=True)
    ...

尝试根据型号获取电子邮件:

class NotificationRecipient(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def get_email_addr(self):
        ''' Gets the model, then pulls the email address. '''
        # Get the model
        # if client:
            # return primary_email
        # elif account:
            # return email

我该怎么做呢?

2 个答案:

答案 0 :(得分:1)

您可以查看ProxyPassReverse /images/ http://imageserver.local/images/ 字段以确定对象的类型。

但是,您可以考虑在所有返回相关属性的目标模型上定义属性,而不是检查类型。

答案 1 :(得分:1)

最好在目标模型上定义方法,而不是在NotificationRecipient模型中构建所有业务逻辑。

逻辑是NotificationRecipient模型只需要知道它需要一个电子邮件地址。

class Client(...):
    def get_email_addr(self):
        return primary_email

class Account(...):
    def get_email_addr(self):
        return email

class NotificationRecipient(models.Model):
    content_type = models.ForeignKey(ContentType)
    object_id = models.PositiveIntegerField()
    content_object = GenericForeignKey('content_type', 'object_id')

    def get_email_addr(self):

        try:
            email = self.content_object.get_email_addr()

        # if you want to enforce the attribute
        except AttributeError:
            raise ImproperlyConfigured('Model requires an email address')

        # if you need a default
        if not email:
            return 'default@email.com'

        return email
相关问题