在Django的views.py中过滤MultiSelectField

时间:2019-11-15 10:59:03

标签: python django

models.py中的产品类

class Product(models.Model):
    category = models.ForeignKey(
        Category,
        related_name='products',
        on_delete=models.CASCADE)
    gender_choice = (
        ('Male', 'Male'),
        ('Female', 'Female'),
    )
    name = models.CharField(max_length=200, db_index=True)
    slug = models.SlugField(max_length=200, db_index=True)
    image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True)
    description = models.TextField(blank=True)
    stock = models.IntegerField(default=0, null=False)
    price = models.DecimalField(max_digits=10, decimal_places=2)
    gender = MultiSelectField(choices=gender_choice)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

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

    def __str__(self):
        return self.name

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

我需要过滤性别。假设我进入登录页面,它显示了电子商务网站上的所有产品。出现“男”和“女”的链接。如果单击“男性”,则仅需要显示属于男性的产品。性别字段是一个MultiSelectField。雌性过滤器也是如此。这些类别仅包含品牌名称,不包含男性和女性。我尝试过这样的事情:

views.py

def product_list2(request, category_slug=None):
    category = None
    categories = Category.objects.all()
    products = Product.objects.filter(available=True, gender='Male')
    if category_slug:
        category = get_object_or_404(Category, slug=category_slug)
        products = products.filter(category=category)
    return render(request,
                  'shop/product/list.html',
                  {'category': category,
                   'categories': categories,
                   'products': products})

请注意行products = Product.objects.filter(available=True, gender='Male')肯定不起作用。如何使它基于MultiselectField过滤对象?感谢您的关注。

0 个答案:

没有答案