Search code examples
pythondjangomodelscategories

Creating SubCategories with Django Models


I am trying to expand the relationships within my Django Models. I have a system where elements are stored within Categories. How do I structure my models.py so that each category is related to a subcategory?

Here is what my category model looks like:

class Category(models.Model):
   site = models.ForeignKey(Site)
   template_prefix = models.CharField(max_length=200, blank=True)
   name = models.CharField(max_length=200)
   slug = models.SlugField() 
   description = models.TextField(default='')
   sortby_fields = models.CharField(max_length=200,
                                 help_text=_(u'A comma separated list of field names that should show up as sorting options.'),
                                 blank=True)
   sort_order = models.PositiveIntegerField(default=0)

   def __unicode__(self):
       return self.name + u' Category'

   class Meta:
       verbose_name_plural = u'categories'

Thanks for any suggestions.


Solution

  • You can create a foreign key to itself:

    class Category(models.Model):
       ...
       parent_category = models.ForeignKey('self', null=True, blank=True)
    

    Then you can assigning any existing Category instance as the parent_category of that instance. Then, if you wanted to find all of the subcategories of a given Category instance you would do something like:

    subcategories = Category.objects.filter(
        parent_category__id=target_category.id)