2015-10-05 61 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