AJNinja
AJNinja

Reputation: 140

Django foreignkey query

class Model1(models.Model):
    a1 = models.CharField()

class Model2(models.Model):
    a2 = models.CharField()
    model1 = ForeignKey(Model1)

I want to do something like this in

#views.py

def action(request):
    model1_instances = Model1.objects.all()
    render_to_respose('action.html', 'model1_instances': model1_instances, context_instance=RequestContext(request)

What i want to do is ;

For each 'model1_instances' object that gets passed to the action.html, i want its corresponding Model2 objects.

Tried using model2_instance = model1_instances.model2_set.all(), it was not giving the desired result and probably because model1_instances returns all the Model1 objects in the database.

What i know

If i use something like;

model1_instance = Model1.objects.get(pk=1)

it is very easy to get the corresponding

model2_instance = model1_instance.model2_set.all().

I know this already and it is not what am looking for.

Need some clues guys.

Solution

Thank you all for your contributions. I stumbled on this [API]: https://github.com/japsu/django-selectreverse and i decided to make use of it. Just like the saying goes "there is no need to re-invent the wheel". It worked and actually saved me a lot of headache and i can now focus my attention on something else.

Upvotes: 1

Views: 213

Answers (3)

AJNinja
AJNinja

Reputation: 140

Thank you all for your contributions. I stumbled on this [API]: https://github.com/japsu/django-selectreverse and i decided to make use of it. Just like the saying goes "there is no need to re-invent the wheel". It worked and actually saved me a lot of headache and i can now focus my attention on something else.

Upvotes: 0

SWilder
SWilder

Reputation: 817

You would get the instance of Model1:

model1 = Model1.objects.get(pk=1)

Then to get the instance of Model2 that referenced it with its FK try this:

model2 = model1.Model2_set.all()

This will return the set of all Model2 instances that reference your instance of Model1.

I got the information for this from: Backwards related objects

EDIT: Get the related Model2 instances in the template rather than view:

{% for model1 in model1_instances %}
    {% for model2 in model1.Model2_set.all %}
    {{ model2 }}
    {% endfor %}
{% endfor %}

Upvotes: 0

SWilder
SWilder

Reputation: 817

I think that the answer you are after has been answered over in another thread.

Best practice to get related values in Django

Off the top of my head though (untested), try something like this:

model2_instance = Model2.objects.filter(model1__pk=1) 

Upvotes: 1

Related Questions