首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Django模型架构

Django模型架构
EN

Stack Overflow用户
提问于 2011-12-01 10:57:26
回答 1查看 221关注 0票数 0

我正在尝试设计支持以下内容的模型:

不同类型的帐户

每个帐户都有多组首选项,这些首选项对于每个帐户类型都是唯一的

设计模型最灵活的方式是什么?

示例:

代码语言:javascript
复制
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

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-12-01 12:33:47

这里有一种可能性:

代码语言:javascript
复制
#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的外键将允许您过滤首选项,以便只显示与正在创建/更新的帐户相关的首选项。

使用AccountType模型可以防止您为当前已在ACCOUNT_CHOICES元组中定义的帐户类型定义单独的类。希望这能帮到你。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8336037

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档