Home > OS >  Filtering data using age group in django
Filtering data using age group in django

Time:07-11

I want to filter my products based on for what age group they are intended to. My plan of doing that is using a boolean field and filter the products by that. I have a dropdown menu which lists the different age groups and when a person clicks on one, a page will be displayed with the products which have boolean true for that age group. Here is my models.

class Product(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE) 
    title = models.CharField(max_length=150)
    image = models.ImageField(null=False, upload_to='images/')
    price = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    amount = models.IntegerField(default=0)
    detail = RichTextUploadingField()
    create_at = models.DateTimeField(auto_now_add=True)
    update_at = models.DateTimeField(auto_now=True)
    child = models.BooleanField(default=False)
    teen = models.BooleanField(default=False)
    adult = models.BooleanField(default=False)

    def __str__(self):
        return self.title

Is this the way I should do it? If it is the case should I use 3 different views.py for each boolean or is there any efficient way? Thank you in advance!

CodePudding user response:

No, you don't need 3 views to show this. You can get the value user submits via a form like this request.GET if you didn't specify any method attribute in the form or for POST request you can get the data using request.POST.
Assuming you are using pure Django with functional-based views. Then your view will look like this.

def get_products(request):

    # getting the gender group you passed via form
    gender_group = request.GET.get("gender_group")

    # assuming you are passing `child`, `teen` and `adult` through from drop-down value
    user_products = Products.objects.filter(**{gender_group: True})

    return render(request, "you_template_name.html", {"products": user_products})

Assuming you html form will be something like this one.

  <form method="get">
        <!-- you other fields -->
      <select name="gender_group">
        <option value="child">Child</option>
        <option value="teen">Teen</option>
        <option value="adult">Adult</option>
      </select>
    </form>

CodePudding user response:

@Mubashar javed you are correct. I just added two things and it worked.

 <Form action="{% url 'get_products' %}" method="get">
  <select name="gender_group">
        <option value="child">Child</option>
        <option value="teen">Teenager</option>
        <option value="adult">Adult</option>
        <input type="submit" value="Submit">
  </select>
 </Form>
  • Related