我只想从djnago的数据库中获取特定类别的产品(女士)产品

时间:2018-11-29 11:46:26

标签: python-2.7 django-models django-templates django-views

 {% regroup products by categories as products_by_category %}
    {% for c in products_by_category %}
       <h1>{{c.grouper}}</h1>
       <ul>
        {% for p in c.list %}
            <li>{{p.name}}</li>
            <li> <img src="{{ MEDIA_URL }}{{ p.image.url }}" alt="IMG-PRODUCT" height="290" width="190"></li>
            <li>{{ p.price }}</li>
        {% endfor %}
       </ul>
    {% endfor %}

这是我的Views.py

def product_list_women(request, category_slug=None):
    category = None
    categories = Category.objects.filter(name='women', slug='women')
    products = Product.objects.filter(available=True)
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=categories)
    return render(request, 'product_women.html',{'category': category,'categories':categories,'products':products})

这是我的models.py文件

class Category(models.Model):
    name = models.CharField(max_length=150, db_index=True)
    slug = models.SlugField(max_length=150, unique=True ,db_index=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        ordering = ('name', )
        verbose_name = 'category'
        verbose_name_plural = 'categories'

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('demo:category', args=[self.slug])

    def get_products(self):
        return Product.objects.filter(category=self)


class Product(models.Model):
    category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE)
    name = models.CharField(max_length=100, db_index=True)
    slug = models.SlugField(max_length=100, db_index=True)
    description = models.TextField(blank=True)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    available = models.BooleanField(default=True)
    stock = models.PositiveIntegerField()
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)

    class Meta:
        ordering = ('name', )
        index_together = (('id', 'slug'),)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('demo:product_detail', args=[self.id, self.slug])

我只想列出女性产品而不是所有产品类别。我要创建一个页面,当我单击该类别时显示产品。此代码明智地显示所有产品类别。< / p>

1 个答案:

答案 0 :(得分:0)

根据Django's Many-to-one relationship Documentation

  

相关的经理也支持字段查找。 API会根据您的需要自动遵循关系。使用双下划线分隔关系。这可以根据需要任意深度地工作。没有限制。

因此,您可以执行以下操作:

products = Product.objects.filter(available=True, category__name='women')