Validation turns out to be well-nigh impossible using parent / child
aliases, but pretty easy with parent / child accounts.  Here's what
I've ended up with:

class Account(models.Model):
        user = models.ForeignKey(User, unique=True, null=True, blank=True)
        alias = models.CharField(max_length=32, unique=True)
        parent_account = models.ForeignKey('self', related_name='children',
null=True, blank=True)

        def __unicode__(self):
                return '%s owned by %s' % (self.alias, self.get_owner())

        def save(self, force_insert=False, force_update=False):
                if not Account.is_valid_parent_or_child(self.user,
self.parent_account):
                        raise AccountInheritanceError
                super(Account, self).save(force_insert, force_update)

        def get_canonical_alias(self):
                if self.is_child():
                        return self.parent_account.get_canonical_alias()
                return self.alias

        def get_owner(self):
                if self.is_child():
                        return self.parent_account.get_owner()
                return self.user

        @staticmethod
        def is_valid_parent_or_child(user, parent_account):
                # We need either a user (meaning this is a primary account)
                # or a parent (meaning this is a child account), but not both
                if bool(user) == bool(parent_account):
                        return False
                if parent_account.is_child():
                        return False
                return True

        def is_parent(self):
                return bool(self.user)

        def is_child(self):
                return bool(self.parent_account)

I'll probably end up shunting any required account fields into a
Profile model and either a)attaching that to Account with a nullable
one-to-one relationship, and making that required for parent accounts;
or b) making the Profile model the AUTH_PROFILE_MODULE rather than
Account (which is currently).
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To post to this group, send email to django-users@googlegroups.com
To unsubscribe from this group, send email to 
django-users+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to