简体   繁体   English

滤波型号Django

[英]Filtering models Django

I have these models in my models.py:我的models.py中有这些模型:

class Category(models.Model):
    main_category= models.ForeignKey(HovedKategori, on_delete=models.CASCADE)
    name= models.CharField(max_length=200)

    def __str__(self):
        return self.name
    
class UnderCategori(models.Model):
    main_kategory= models.ForeignKey(Category, on_delete=models.CASCADE)
    supplier = models.CharField(max_length=200)
    price = models.IntegerField()
    title = models.CharField(max_length=200)
    img = models.CharField(max_length=200)
    info= models.CharField(max_length=200)
    link= models.CharField(max_length=200)


    def __str__(self):
        return str(self.supplier ) + " " + str(self.title)
    

Ho do i query all the different category suppliers without repeating them?如何不重复查询所有不同类别的供应商? What i mean is if i have 10 different suppliers with 500 products combined how do i query the 10 different suppliers.我的意思是,如果我有 10 个不同的供应商和 500 种产品,我该如何查询这 10 个不同的供应商。 Also im not sure if this is the correct data stucture i should use, if there are any tips on that, that would also be appretiated.我也不确定这是否是我应该使用的正确数据结构,如果有任何提示,那也将不胜感激。

I would suggest splitting the supplier from the category like so:我建议将供应商从类别中分离出来,如下所示:

class Supplier(models.Model):
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name

class Category(models.Model):
    main_category = models.ForeignKey(HovedKategori, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)

    def __str__(self):
        return self.name
    
class UnderCategori(models.Model):
    main_kategory= models.ForeignKey(Category, on_delete=models.CASCADE)
    supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
    price = models.IntegerField()
    title = models.CharField(max_length=200)
    img = models.CharField(max_length=200)
    info= models.CharField(max_length=200)
    link= models.CharField(max_length=200)

    def __str__(self):
        return str(self.supplier ) + " " + str(self.title)

Then you could simply do Supplier.objects.all()然后你可以简单地做Supplier.objects.all()
Please note that I don't really understand why there are two different categories.请注意,我真的不明白为什么有两个不同的类别。 Perhaps one is a sub-category?也许一个是子类别? Also, you are talking about products, not categories.此外,您在谈论产品,而不是类别。 I don't see any 'products' mentioned in your code我没有在您的代码中看到任何“产品”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM