Home > Blockchain >  How i can make this filter
How i can make this filter

Time:06-16

I want to create filter for cars by marks, and idk why, i get empty template with list of objects I have this model with Foreignkey mark model for getiing mark for specify car

class Product(models.Model):

    ENGINE_CHOICES = (
    ('Бензин', 'Бензин'),
    ('Дизель', 'Дизель'),
    )

    code = models.AutoField(primary_key=True)
    country = models.ForeignKey(Country, on_delete=models.CASCADE)
    mark = models.ForeignKey(Mark, on_delete=models.CASCADE, related_name='mark')
    model = models.CharField(max_length=45)
    color = models.CharField(max_length=45)
    availability = models.BooleanField()
    price = models.PositiveIntegerField()
    image = models.CharField(max_length=64, null=True)
    slug = models.SlugField(blank=True)
    year = models.PositiveSmallIntegerField("Дата выхода", default=2019, null=True)
    draft = models.BooleanField('Черновик', default=False)
    cat = models.ForeignKey(Category, verbose_name='Категории', on_delete=models.PROTECT, null=True)
    description = models.TextField(max_length=500, null=True)
    engine = models.CharField(choices=ENGINE_CHOICES, max_length=20, blank=True, null=True)

And this model

class Mark(models.Model):
    code = models.AutoField(primary_key=True)
    title = models.CharField(max_length=45)

    def __str__(self):
        return self.title

i have this component in html for getiing mark in vews

      <div id="myDropdown7" >
        {% for mark in marks %}
          <form action="{% url 'filtration_marks' %}" method="GET">
            <label class='dropdown-content-menu'>
              <input id='checkbox1' type="checkbox" class='checkbox' name="mark" value="{{ mark.title }}">
              <label for='checkbox1'></label>
              <button type="submit" style="border: 0; background-color: white; font-size: 16px;">{{ mark.title }}</button>
          </label>
        </form>
          {% endfor %}

And this method in views that handle request

def filtration_marks(request):

    products = Product.objects.filter(mark__in=request.GET.getlist('mark'))
    categories = Category.objects.all()
    marks = Mark.objects.all()

    context = {
        'products': products,
        'categories': categories,
        'marks': marks,
    }

    return render(request, 'filtration.html', context=context)

CodePudding user response:

You should filter on the title of the mark, so:

products = Product.objects.filter(mark__title__in=request.GET.getlist('mark'))

CodePudding user response:

If the request had a list of ids code in your case, So the filter would be:

products = Product.objects.filter(mark_code__in=request.GET.getlist('mark'))

However, If the request had a list of titles, So it would be:

products = Product.objects.filter(mark__title__in=request.GET.getlist('mark'))
  • Related