Efrin
Efrin

Reputation: 2423

Django - filtering related objects in "backward" relationships

I've been working on some models with "backward" relationships. I started wondering... What if I want to filter some results?

I've got two models:

Model A:
 name
 image
 date 

Model B:
 ForeignKey to Model A
 name
 date

To access model A I use: p = A.objects.all().order_by('-date')

and I pass that to template.

In template:

{% for n in model_a.all %}
  {% for item in n.modelb_set.all %}

   <li>{{item.name}}</li>

  {% endfor %}
{% endfor %}

I get all backward related objects for model A and thats fine.

Now what if I want to filter some results from that query?

I was thinking of iteration in a View by:

p = A.objects.all().order_by('-date')

for n in p:
    for x in n.modelb_set.filter(date_lte=""):
    ls = []
    ls.append[x]

How do I pass that to the template and get what I got earlier (unfiltered view) but now with filtered results?

Upvotes: 0

Views: 1389

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239270

The best way is to add a method to your model. It would be easier to illustrate with a real world model example, but the gist is:

class ModelA:
    ...
    def filtered_modelb_set(self):
        return self.modelb_set.filter(...)
    ...

Then, in your template, you just call that method instead:

{% for n in model_a.all %}
    {% for item in n.filtered_modelb_set %}

    <li>{{item.name}}</li>

    {% endfor %}
{% endfor %}

Upvotes: 5

Related Questions