I have a list of categories that allows you to set a parent/child
relationship such as:

  Financial
  Financial > Billing
  Financial > Billing > Collections
  Financial > Invoices

In the example above, "Financial" is a category, then "Billing" is a
category with "Financial" as the parent, etc.


I've got two problems I'm trying to solve:

1. Users shouldn't be able to set the parent object as itself

This can happen if save a category, then go back in and edit it. With
the way I'm returning the get_full_name() method, this causes a
recursion problem.

Is there a way to filter the current object out of the parent dropdown
in the admin? This should be pretty easy to do with logic outside of
the admin, but I'd like it to work properly inside the admin as well.
I was trying to find a way to use a pre or post-save hook to see if
the new value being saved for parent was equal to the object's ID and
causing a validation error, but couldn't quite nail it.

2. I'd like to group the subcategories by their parent categories all
the way down the hierarchy

I thought about trying to use the flattened hierarchy in a character
field and sorting by that (which worked) but if a parent category
changed, you have to go through and resave all the categories and
their flattened structures again to update them. That could work, but
it doesn't feel like the right approach.

I'm at a loss for ideas, does anyone have a clever solution for me?

Here's the model:

class Category(models.Model):
    name = models.CharField(max_length=200)
    parent = models.ForeignKey('self', null=True, blank=True)

    def get_full_name(self):
        if self.parent:
            return "%s: %s" % (self.parent.get_full_name(), self.name)
        else:
            return self.name

    def save(self, force_insert=False, force_update=False):
        # Don't let people save itself as parent
        if self.id and self.parent:
            if self.id == self.parent.id:
                return False
        super(Category, self).save(force_insert, force_update)

    def __unicode__(self):
        return self.get_full_name()


--~--~---------~--~----~------------~-------~--~----~
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 [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/django-users?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to