如何从产品中获取类别?Django

huangapple go评论80阅读模式
英文:

How to get Category from Product? Django

问题

我试图创建一个搜索栏,用户可以选择类别并输入产品名称。这样我就可以显示所有与用户在文本输入中输入的产品名称匹配的该类别中的产品。

所以我有 Category -> Subcategory -> Product。有没有办法从 Product 模型中获取 Category 对象?(我在产品模型中没有类别字段)

以下是我的 models.py 文件:

# models.py

class Category(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name_plural = 'Categories'

    def __str__(self):
        return self.name

class Subcategory(models.Model):
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='subcategories')
    name = models.CharField(max_length=200, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    top5 = models.BooleanField(default=False, null=True, blank=True)
    featured = models.BooleanField(default=False, null=True, blank=True)

    class Meta:
        verbose_name_plural = 'Subcategories'

    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200, null=True, blank=True)
    subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True, related_name='products')
    image = models.ImageField(null=True, blank=True, upload_to='products/')
    price_old = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
    price_new = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
    description = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.name

正如您所看到的,我尝试创建一个属性来获取类别,但现在我在筛选共享相同类别的产品方面遇到了困难。

以下是我的 views.py 文件:

def search_products(request):
    q = request.GET.get('q') if request.GET.get('q') is not None else ''
    category = Category.objects.get(name=request.GET['category'])
    products = Product.objects.filter(name__icontains=q, subcategory__category=category)  # <-- 这一行

    context = {'products': products, 'q': q}
    return render(request, 'search_products.html', context)

如果您有任何想法,我会非常高兴听到您的建议!

英文:

I'm trying to create a search bar where user can choose Category and write product name. So I can display all products in that category where the name of product matches with what he wrote in text input.

So I have Category -> Subcategory -> Product. Is there any way to get Category object from Product model? (I don't have field for category in product model)

Here is my models.py file:

# models.py

class Category(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    class Meta:
        verbose_name_plural = &#39;Categories&#39;
    def __str__(self):
        return self.name
    
class Subcategory(models.Model):
    category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name=&#39;subcategories&#39;)
    name = models.CharField(max_length=200, null=True, blank=True)
    created = models.DateTimeField(auto_now_add=True)
    top5 = models.BooleanField(default=False, null=True, blank=True)
    featured = models.BooleanField(default=False, null=True, blank=True)
    class Meta:
        verbose_name_plural = &#39;Subcategories&#39;
    def __str__(self):
        return self.name

class Product(models.Model):
    name = models.CharField(max_length=200, null=True, blank=True)
    subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_NULL, null=True, related_name=&#39;products&#39;)
    image = models.ImageField(null=True, blank=True, upload_to=&#39;products/&#39;)
    price_old = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
    price_new = models.DecimalField(decimal_places=2, max_digits=7, null=True, blank=True)
    description = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return self.name

    # @property
    # def category(self):
    #     return self.subcategory.category

Here as you can see I tried to create a property to get the category, but now I'm struggling to filter products that share the same category

Here is my views.py file:

def search_products(request):
    q = request.GET.get(&#39;q&#39;) if request.GET.get(&#39;q&#39;) != None else &#39;&#39;
    category = Category.objects.get(name=request.GET[&#39;category&#39;])
    products = Product.objects.filter(name__icontains=q, category=category) &lt;-- This line

    context = {&#39;products&#39;:products, &#39;q&#39;:q}
    return render(request, &#39;search_products.html&#39;, context)

If you have any ideas, I would be really glad to hear you!

答案1

得分: 0

是的。由于您的 Product 模型有一个外键指向 Subcategory,而 Subcategory 有一个外键指向 Category,您可以在模板中执行以下操作:

{% for product in products %}
 分类{{ product.subcategory.category }}
 产品{{ product }}</div>
{% endfor %}

要进行筛选,您应该使用双下划线 (__) 语法:

products = Product.objects.filter(
    name__icontains=q, 
    subcategory__category=category
)
英文:

Yes. Since your Product model have a foreign key to Subcategory, and Subcategory has a foreign key to Category, you can do the following in your template:

{% for product in products %}
 Category: {{ product.subcategory.category }}
 Product: {{ product }}&lt;/div&gt;
{% endfor %}

To filter them, you should use the double underscore (__) syntax:

products = Product.objects.filter(
    name__icontains=q, 
    subcategory__category=category
)

huangapple
  • 本文由 发表于 2023年6月22日 11:57:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528517.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定