在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
?任何帮助,将不胜感激!预先感谢!
答案 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()