开发者

django: child categories and their parents

I've built a website that categorizes products in categories and children (sub) categories.

These are my models:

class Category(models.Model):
    name = models.CharField(max_length=250)
    parent = models.ForeignKey('self', related_name='children')
    ...

class Product(models.Model):
    category = models.ForeignKey(Category)
    name = models.CharField(max_length=250)
    ...

On the view that renders the categories, I have this:

def some_view(request, category):
    category_list = Category.objects.filter(parent__isnull=True)
    product_list = Product.objects.filter(category=category)

My template shows everything correctly:

<ul>
    {% for category in category_list %}
    <li>
        <a href="{{ category.get_absolute_url }}">{{ category.name }}</a>
        <ul>
            {% for child in category.children.all %}
            <li><a href="{{ child.get_absolute_url }}">{{ child.name }}</a></li>
            {% endfor %}
        </ul>
    </li>
    {% endfor %}
</ul>

I can successfully display the categories and their children. My problem is that I'm using sub-categories to further filter down products, but they should also belong to the main category. For example:

Books
--- Comics
--- Sci-Fi
--- ...
Music
--- Classical
--- Pop
--- ...

If I classify a product in "Books > Comics", I will get that product if I select "Comics" in the catego开发者_JAVA技巧ry listing in my template. But, selecting "Books" should also list that product because it is the top category, but it doesn't show any products unless I categorize them as the parent category "Books". I'm not sure how to explain this in a better way, but I basically want to be able to show all products that belong to a sub-category, but when I select the main category, that product should be there as well, and I can't seem to make it work. Any suggestions, please?


Off the top off my head, the simplest to implement would be,

change the foreign key from product to category to many-to-many, then override your model save such that it automatically assigns the parent category to the product for every category.

But a better solution would be (i read your comment, im still saying this), implement django-mptt and use south [http://south.aeracode.org/docs/tutorial/part3.html] to handle the datamigration.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜