在购物Django res中按类别筛选品牌

2024-10-04 03:28:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django Rest框架中通过Category过滤Brand时面临问题

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部分时,我应该得到Shoes类别中的所有品牌。为此,我如何编写query_set?任何帮助都将不胜感激!提前谢谢


Tags: nametruemodels类别nulllengthmaxclass
1条回答
网友
1楼 · 发布于 2024-10-04 03:28:37

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

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()

相关问题 更多 >