python - 从父类别的django rest获得所有产品-LMLPHP例如,我有与子类别相关的产品:我有类似的类别

ToysToys -> ChildToysToys -> ChildToys -> Cars我有与Toys -> ChildToys -> Cars相关的产品,我可以通过Cars获得所有产品,但是如何通过过滤Toys类别来获得产品。到目前为止我做了什么

class Category(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, blank=True, unique=True)
    icon = models.ImageField(upload_to='category_icons', null=True, blank=True)
    parent = models.ForeignKey('self', on_delete=models.SET_NULL, related_name='children', null=True, blank=True)


class Product(models.Model):
    category = models.ForeignKey(Category, blank=True, null=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)

class ProductList(generics.ListAPIView):
    serializer_class = ProductSerializer

  def get_queryset(self):
    slug = self.request.query_params.get('slug', None)
    parent_id = Category.objects.get(slug=slug)
    cats = Category.objects.filter(parent_id=parent_id)

    qs = Product.objects.filter(category_id__in=parent_id)

    print(qs)
    return qs

最佳答案

如果需要下降整个子树,则需要在Category模型上创建一个递归获取所有子类别的方法。 another post向您显示如何执行此操作。

因此,假设您具有该方法Category.get_family_tree()

class Category(models.Model):
    # fields
    def get_family_tree(self):
        # code from question linked above
        # returns list of `Category` instances


然后您认为可以提取以下产品:

def get_queryset(self):
    slug = self.request.query_params.get('slug')
    categories = Category.objects.get(slug=slug).get_family_tree()
    return Product.objects.filter(category__parent__in=categories)

关于python - 从父类别的django rest获得所有产品,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59267201/

10-12 18:50