Django Category and Subcategory searches

后端 未结 3 495
闹比i
闹比i 2021-02-04 17:08

I\'m attempting to use a similar Category implementation to this one in the Django Wiki. I\'m wondering what the Django way of doing a search to pull all objects associated wit

3条回答
  •  误落风尘
    2021-02-04 17:43

    Assuming you're using the Category model the same way it's being used on the page you referenced, it would seem that a category 'TV' would be a Category instance with a null parent, and 'Plasma' & 'LCD' would be Category instances with the 'TV' category as a parent.

    >>> tv=Category(name="TV")
    >>> tv.save()
    >>> lcd=Category(name="LCD", parent=tv)
    >>> lcd.save()
    >>> plasma=Category(name="Plasma", parent=tv)
    >>> plasma.save()
    

    Create some items

    >>> vizio=Item(name="Vizio", category=lcd)
    >>> vizio.save()
    >>> plasmatron=Item(name="PlasmaTron", category=plasma)
    >>> plasmatron.save()
    

    Get the Item queryset

    >>> items=Item.objects.filter(category__parent=tv)
    

    or

    >>>> items=Item.objects.filter(category__parent__name='TV')
    

    Does this look like it's in the ballpark of what you need?

提交回复
热议问题