squish
squish

Reputation: 51

Django - select object from DB in a template

I have something like:

{% for mother in mothers_list %}
    {% for father in fathers_list %}
        {% Child.objects.get(mother=mother, father=father) as child %}
            child.name

Unfortunately, I can't call a function with parameters from the template, so this line

{% Child.objects.get(mother=mother, father=father) as child %}

wont work. Any ideas of how how can I get the Child object each time?

Upvotes: 0

Views: 290

Answers (3)

nimasmi
nimasmi

Reputation: 4138

You could do this processing in the view function.

In views.py:

children_list = []
for mother in mothers_list:
    for father in fathers_list:
        try:
            child = Child.objects.get(mother=mother, father=father)
        except Child.DoesNotExist:
            child = None
        children_list.append(child)

Then in your template:

{% for c in children_list %}
    {{ c.name }}

Upvotes: 0

Tauquir
Tauquir

Reputation: 6913

you can write a custom template tags for this and this will be like:

In your project/templatetags/custom_tags.py:

    from django.template import Library
    register = Library()
    @register.filter
    def mother_father(mother_obj, father_obj):
            // Do your logic here
            // return your result 

In template you use template tags like:

{% load custom_tags %}

{% for mother in mothers_list %}
    {% for father in fathers_list %}
        {{ mother|mother_father:father }}

Upvotes: 2

rczajka
rczajka

Reputation: 1840

Read https://docs.djangoproject.com/en/dev/howto/custom-template-tags/ and write a custom tag.

Upvotes: 0

Related Questions