san
san

Reputation: 11

filtering your database

i have a model which gives me the details of some cheese, now i use it in a list view, i have also implemented a search function,which works all fine. now i want to add filter tabs on the html. eg: the origin of cheese is only from 5 countries, i want to display the flags icons of 5 countries which when clicked should only display the cheeses from that particular countries, just like mixitup, im ok if there is no animation thing. how can i acheive this???? note: the models and views and html is written the normal way incase if you want see my code.

MODELS.PY

class Cheese(models.Model):

    TYPES_CHOICES=(
        ('COW', 'COW'),
        ('GOAT', 'GOAT'),
        ('SHEEP', 'SHEEP'),
        ('BUFFALO', 'BUFFALO'),
        ('COW, GOAT & SHEEP',  'COW, GOAT & SHEEP'),
        ('COW & SHEEP',  'COW & SHEEP')
    )

    COUNTRY_CHOICES=(
        ('USA', 'USA'),
        ('UK','UK'),
        ('ITALY', 'ITALY'),
        ('FRANCE', 'FRANCE'),
        ('NETHERLANDS', 'NETHERLANDS')
    )

    origin = models.CharField(max_length=100)
    title =  models.CharField(max_length=100)
    types =  models.CharField(max_length=100, choices=TYPES_CHOICES)
    about =  models.TextField()
    serve =  models.CharField(max_length=1000)
    image = models.ImageField(
        null=True, 
        blank=True,
        width_field="width_field",
        height_field= "height_field")
    width_field = models.IntegerField(default=550)
    height_field = models.IntegerField(default=550)
    country = models.CharField(max_length=50, choices=COUNTRY_CHOICES)
    timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)

    def __unicode__(self):
        return self.title

Upvotes: 1

Views: 65

Answers (1)

Borko Kovacev
Borko Kovacev

Reputation: 1020

Unsure if you're using basic requests or are you using Class Based Views. There is a neat library called django-filters. A stackoverflow answer with the example of implementation.

If you're making custom views - I would make the queries as follows:

I'd make a Cheese.objects.filter(country='USA') for a specific country and if you're trying to filter by multiple states Cheese.objects.filter(country__in=['USA', 'FRANCE'].

Upvotes: 1

Related Questions