2015-10-05 28 views
1

我有一个自定义的用户数据轮廓模型:如何设置Django的用户选项通用模型

class Profile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False) 
    # more stuff... 

我也有一个通知应用程序,允许模型发送通知和电子邮件给用户。

我希望用户可以选择开启或关闭不同的通知选项,但我不希望布尔领域的一个巨大的列表添加到配置文件是这样的:

class Profile(models.Model): 
    user = models.OneToOneField(settings.AUTH_USER_MODEL, null=False) 
    send_model1_notice1 = models.BooleanField() 
    send_model1_email1 = models.BooleanField() 
    send_model1_notice2 = models.BooleanField() 
    send_model1_email2 = models.BooleanField() 
    send_model2_notice1 = models.BooleanField() 
    send_model2_email1 = models.BooleanField() 
    send_model3_notice1 = models.BooleanField() 
    send_model3_email1 = models.BooleanField() 
    # etc... 

其中modelx一些模型或其他一些应用程序是通知的来源,noticex/emailx是通知的一些具体原因。

我在想更可持续的做法是创建一个ProfileOptions模型,外部模型可以用它来定义他们自己的通知设置。

这样,当我添加一个新的应用程序/模型时,我可以以某种方式将其通知源链接到ProfileOptions模型,并让这些选项将它们打开或关闭以神奇的方式显示在用户的配置文件中。

这是否有意义?如果是这样,可能吗?如果是的话,这是一个好主意吗?如果是这样,我应该使用什么结构来连接模型,ProfileOptions和用户的配置文件?

很显然,我希望能够回答最后一个问题,但我不想排除对其他人的回答可能是“不”的可能性。

回答

0

一种方法是将有一个单独的Notification模型,链接两个:

from django.contrib.contenttypes.fields import GenericForeignKey 
from django.contrib.contenttypes.models import ContentType 

class Notification(models.Model): 
    # Foreign key to user profile 
    user = models.ForeignKey(Profile) 

    # Generic foreign key to whatever model you want. 
    src_model_content_type = models.ForeignKey(ContentType) 
    src_model_object_id = models.PositiveIntegerField() 
    src_model = GenericForeignKey('src_model_content_type', 'src_model_object_id') 

    # Notification on or off. Alternatively, only store active notifications. 
    active = models.BooleanField() 

这种做法将让你处理源模型的通知任意数量(每个通知的任意数字),而不会试图将所有通知信息挤入您的用户配置文件中。

+0

我很困惑,我已经有一个'Notification'模型(如上所述)。你的意思是这可能是我提到的'ProfileOptions'模型? – 43Tesseracts

+0

你的问题说你有一个“通知应用程序” - 不是有一个模型 - 许多应用程序没有模型:-)。在任何情况下,假设所有选项都具有相同的类型(例如布尔型开/关),那么这可能是您的'ProfileOption'模型,充当'Profile'和其他任意定义的模型之间的链接。 – solarissmoke