2011-12-01 62 views
0

我想設計模式,將支持以下內容:Django的模型體系

不同類型的帳戶

每個帳戶都有所特有的每個賬戶類型

有什麼喜好的多組最靈活的方式來設計模型?

例子:

Account Type Swimmer 
    Location 
    Email 
    ID 
    Preferences 
     Swimming 
      Lake 
      Sea 
     Running 
      Beach 
     Bike 
      Road 

Account Type Doctor 
    Location 
    Email 
    ID 
    Preferences 
     Reading 
      Magazines 
     Food 
      Veggies 

Account Type Runner 
    Location 
    Email 
    ID 
    Preferences 
     Swimming 
      Ocean 
     TV 
      Sports Channels 

model.py

class Account (models.Model): 
    #common account attributes such as email, name 
    ACCOUNT_CHOICES = (
     ("swimmer", "Swimmer"), 
     ("doctor", "Doctor"), 
    ) 


class PreferencesSwimmer(Account): 
    #Swimmer's Preferences 

class PreferencesDoctor(Account): 
    #Doctor's Preferences 

回答

2

這裏有一個可能性:

#models.py 
class SimpleModel(models.Model): 
    class Meta: 
     abstract = True 

    title = models.CharField(max_length=50) 


class AccountType(SimpleModel): 
    """Groups preferences by, and defines account types""" 


class Category(SimpleModel): 
    """Groups preferences""" 


class Preference(SimpleModel): 
    account_type = models.ForeignKey(AccountType) 
    category = models.ForeignKey(Category) 


class Account(models.Model): 
    account_type = models.ForeignKey(AccountType) 
    email = models.EmailField() 
    last_name = models.CharField(max_length=20) 
    first_name = models.CharField(max_length=20) 
    preferences = models.ManyToManyField(Preference, null=True) 

#forms.py 
class AccountForm(forms.ModelForm): 
    class Meta: 
     model = Account 

    def __init__(self, account_type, *args, **kwargs): 
     super(AccountForm, self).__init__(*args, **kwargs) 
     self.fields['preferences'] = \ 
      forms.ModelMultipleChoiceField(
       queryset=Preferences.objects.filter(account_type=account_type)) 

在ACCOUNT_TYPE到AccountForm傳遞及形成外鍵ACCOUNTTYPE偏好模式將允許您過濾首選項以僅顯示那些perta進入正在創建/更新的帳戶。

擁有AccountType模型可以防止您爲當前已在ACCOUNT_CHOICES元組中定義的帳戶類型定義單獨的類。希望能幫助你。