# How to filter objects based on TextChoices ?

**URL:** <https://forum.djangoproject.com/t/how-to-filter-objects-based-on-textchoices/6779>\
**Category:** Using Django\
**Created:** [February 25, 2021, 9:22pm UTC](https://forum.djangoproject.com/t/how-to-filter-objects-based-on-textchoices/6779 "2021-02-25T21:22:35Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![pitagora04](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pitagora04/32/1019_2.png) [@pitagora04](https://forum.djangoproject.com/u/pitagora04)\
**Post date:** [February 25, 2021, 9:22pm UTC](https://forum.djangoproject.com/t/how-to-filter-objects-based-on-textchoices/6779/1 "2021-02-25T21:22:35Z")

</div>

I’m using `TextChoices` to define Food category - see this example:

```auto
class CategoryChoice(models.TextChoices):
	# Fruits: T01-T50
    T01 = 'T01', 'Apple'
    T02 = 'T02', 'Banana'
    T03 = 'T03', 'Blackberries'
    T04 = 'T04', 'Cherries'
    T05 = 'T05', 'Cranberries'
    # Vegatables: T41-T60
    T41 = 'T41', 'Asparagus'
    T42 = 'T42', 'Broccoli'
    T43 = 'T43', 'Carrot'
	# Meat: T61-T99
    T61 = 'T61', 'Beef'
    T62 = 'T62', 'Lamb'
    T63 = 'T63', 'Pork'

class Food(models.Model):
    name = models.CharField(max_length=30)
    category = models.CharField(
        max_length=3,
        choices=CategoryChoice.choices,
        default=CategoryChoice.T01
    )

```

**How can I properly query only Food objects which have category between T41 and T60 using `Food.objects.filter()` ?**

---

<div class="post-metadata">

**Author:** ![KenWhitesell](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/kenwhitesell/32/280_2.png) [@KenWhitesell](https://forum.djangoproject.com/u/KenWhitesell)\
**Post date:** [February 25, 2021, 9:28pm UTC](https://forum.djangoproject.com/t/how-to-filter-objects-based-on-textchoices/6779/2 "2021-02-25T21:28:48Z")

</div>

If you’re sure that these lists sort properly and aren’t going to create any odd edge cases, you could use the [`__gte`](https://docs.djangoproject.com/en/3.1/ref/models/querysets/#gte) and [`__lte`](https://docs.djangoproject.com/en/3.1/ref/models/querysets/#lte) comparisons. (However, I personally discourage this type of comparison because according to sort order, ‘T415’ comes between ‘T41’ and ‘T42’.)

I would recommend using the [`__in`](https://docs.djangoproject.com/en/3.1/ref/models/querysets/#in) comparison.

---

<div class="post-metadata">

**Author:** ![pitagora04](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/pitagora04/32/1019_2.png) [@pitagora04](https://forum.djangoproject.com/u/pitagora04)\
**Post date:** [February 26, 2021, 9:42am UTC](https://forum.djangoproject.com/t/how-to-filter-objects-based-on-textchoices/6779/3 "2021-02-26T09:42:23Z")

</div>

Thanks, yes it’s bad approach but it’s the fastest way to solve it 🙂 otherwise I would have to rethink the desing…
