howtodothis
howtodothis

Reputation: 1295

Django Model Architecture

I am trying to design model that will support the following:

Different types of accounts

Each account has multiple groups of preferences that are unique to each account type

What's the most flexible way to design the model?

Example:

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

Upvotes: 0

Views: 231

Answers (1)

Brandon Taylor
Brandon Taylor

Reputation: 34553

Here's one possibility:

#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))

Passing in the account_type to the AccountForm and having a foreign key to the AccountType in the Preference model would allow you to filter the Preferences to only show the ones that pertain to the Account being created/updated.

Having the AccountType model prevents you from defining separate classes for the types of accounts that you currently have defined in the ACCOUNT_CHOICES tuple. Hope that helps you out.

Upvotes: 2

Related Questions