# Writing on-request filtering for related objects

**URL:** https://forum.djangoproject.com/t/writing-on-request-filtering-for-related-objects/9909
**Category:** Using Django
**Created:** [September 29, 2021, 5:02pm UTC](https://forum.djangoproject.com/t/writing-on-request-filtering-for-related-objects/9909 "2021-09-29T17:02:54Z")
**Posts on this page:** 4
**Page:** 1

<div class="post-metadata">

### Author: ![tragicomic](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tragicomic/32/2285_2.png) [@tragicomic](https://forum.djangoproject.com/u/tragicomic)
#### Post date: [September 29, 2021, 5:02pm UTC](https://forum.djangoproject.com/t/writing-on-request-filtering-for-related-objects/9909/1 "2021-09-29T17:02:54Z")

</div>

Suppose that we have following models

```auto
   class Category(models.Model):
        name = models.CharField(max_length=254)
    
    class Item(models.Model):
        category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="items")
        name = models.CharField(max_length=254)
        state = models.ForeignKey(State, on_delete=models.CASCADE)

```

Categories and their items are listed like so

```auto
    def view(request):
       categories = Category.objects.all()
       pass

    {% for category in categories %}
    	{{ category.name }}
        {% for item in category.items.all %}
            {{ item.name }}
        {% endfor %}
    {% endfor %}

```

In this structure, I want to write on-request filtering for listed ‘items’.

```auto
    def view(request):
        ...
        queryset = ???
        state = request.GET.get('state')
        if state:
        	queryset = queryset.filter(state__name=state)

```

The problem is defining ‘queryset’. Because, Items are listed as related objects of category.

Can it be done properly? or Do I need to change design?

You can take a look at my low fidelity design to be more clear.

 ![Screenshot from 2021-09-29 18-08-24](https://us1.discourse-cdn.com/flex026/uploads/djangoproject/original/2X/9/9e6b8dfbdc26c3c16853f8fe4b5f76a0c21ddc2b.png)

---

<div class="post-metadata">

### Author: ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)
#### Post date: [September 29, 2021, 8:05pm UTC](https://forum.djangoproject.com/t/writing-on-request-filtering-for-related-objects/9909/2 "2021-09-29T20:05:55Z")

</div>

You could use a [`Prefetch`](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.Prefetch) object. Give that a look and let me know if you have questions.

---

<div class="post-metadata">

### Author: ![tragicomic](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/tragicomic/32/2285_2.png) [@tragicomic](https://forum.djangoproject.com/u/tragicomic)
#### Post date: [September 29, 2021, 10:02pm UTC](https://forum.djangoproject.com/t/writing-on-request-filtering-for-related-objects/9909/3 "2021-09-29T22:02:09Z")

</div>

@CodenameTim, Thank you for the reply.

Firstly, I’m trying to get queryset using [Prefetch](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#django.db.models.Prefetch).

In the document, the sample is,

> ` Question.objects.prefetch_related(Prefetch('choice_set')).get().choice_set.all()`

So when I use this for me,

> `items = Category.objects.prefetch_related(Prefetch('items')).get().items.all()`

**error** : MultipleObjectsReturned → get() returned more than one Category – it returned 8!

* * *

Then, I try to use filter() instead of get()

> `items = Category.objects.prefetch_related(Prefetch('items')).filter().items.all()`

**error** : QuerySet’ object has no attribute ‘items’

How can I fix this?

---

<div class="post-metadata">

### Author: ![CodenameTim](https://sea2.discourse-cdn.com/flex026/user_avatar/forum.djangoproject.com/codenametim/32/31507_2.png) [@CodenameTim](https://forum.djangoproject.com/u/CodenameTim)
#### Post date: [October 4, 2021, 7:08pm UTC](https://forum.djangoproject.com/t/writing-on-request-filtering-for-related-objects/9909/4 "2021-10-04T19:08:42Z")

</div>

It sounds like there may be a misunderstanding with some other parts of the ORM. The first error, [MultipleObjectsReturned](https://docs.djangoproject.com/en/3.2/ref/models/class/#django.db.models.Model.MultipleObjectsReturned), is because [`.get()`](https://docs.djangoproject.com/en/3.2/ref/models/querysets/#get) expects one and only one value to be returned, otherwise it errors. It’s defensive mechanism of the ORM. You may be interested in the `.first()` function when you really only care about getting some value or `None` back. Please check out the ORM’s [queryset documentation](https://docs.djangoproject.com/en/3.2/ref/models/querysets/) for more extensive information.

The second error is due to attempting to access the property `items` which is does not exist on a `QuerySet` which is what’s being returned by `.filter()`. If you’re looking to explore the orm, try `.first()` to get an instance rather than `get`, but be careful of the implications.
