在购物django rest中按类别过滤品牌

时间:2019-10-28 08:46:17

标签: python django django-models django-rest-framework

在Django Rest Framework中用Brand过滤Category时遇到问题。

class Category(TimeStamp):
    name = models.CharField(max_length=100)
    slug = models.SlugField(max_length=100, unique=True, blank=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 Brand(models.Model):
    brand_name = models.CharField(max_length=150)
    brand_image = models.ImageField(upload_to='brand_images', null=True, blank=True)
    category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True)

这里有两个模型。例如,我有一个类似Clothing -> Foot Wear -> Shoes的类别,如果用户输入Clothing类别,我应该获得Clothing中的所有品牌,但是当我进入Shoes部分时,我应该获得{ {1}}类别。为此,我该如何写Shoes?任何帮助,将不胜感激!预先感谢!

1 个答案:

答案 0 :(得分:1)

将相关名称添加到类别外键

category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, null=True, related_name="brands")

然后

clothing_category = Category.objects.get(name="Clothing")
clothing_brands = clothing_category.brands.all()

shoe_category = Category.objects.get(name="Shoes")
shoe_brands = shoe_category.brands.all()