我正在尝试设计支持以下内容的模型:
不同类型的帐户
每个帐户都有多组首选项,这些首选项对于每个帐户类型都是唯一的
设计模型最灵活的方式是什么?
示例:
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 Channelsmodel.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发布于 2011-12-01 12:33:47
这里有一种可能性:
#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元组中定义的帐户类型定义单独的类。希望这能帮到你。
https://stackoverflow.com/questions/8336037
复制相似问题