2011-12-01 34 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元组中定义的帐户类型定义单独的类。希望能帮助你。