vlad
vlad

Reputation: 855

Grouping models in template

I have two related models:

class Package(models.Model):
    package_name = models.CharField(max_length=64)
    ptype = models.CharField(max_length=16)

class Extra(models.Model):
    package = models.ForeignKey(Package, related_name='package')
    data = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True)
    information = models.CharField(max_length=1024, blank=True)

view.py:

def show_package(request):
    list = get_list_or_404(Package, ptype='sometype')
    return render(request, 'table.html', {'list': list})

and template:

{% for row in list %}
<table class="provider_list">
 <tr>
     <td>{{ row.package_name}}</td>
     <td>{{ row.ptype }}</td>
</tr>
</table>
{% endfor %}

How can I add an additional table (from Extra model) next to the prelated table?

Like:

<table>
{% for extra_row in extra_list %}
<tr>
    <td>{{ extra_row.data }}</td>
    <td>{{ extra_row.information }}</td>
</tr>
{% endfor %}
</table>

Thanks.

Upvotes: 1

Views: 92

Answers (2)

arie
arie

Reputation: 18972

try this:

{% for package in list %}
    <table class="provider_list">
        <tr>
             <td>{{ package.package_name}}</td>
             <td>{{ package.ptype }}</td>
             <td>
                <!-- fetch the related data -->
                <table>
                {% for extra in package.extra_set.all %}
                    <tr>
                        <td>{{ extra.data }}</td>
                        <td>{{ extra.information }}</td>
                    </tr>
                {% endfor %}
                </table>
             </td>
        </tr>
    </table>
{% endfor %}

Upvotes: 1

Narsilou
Narsilou

Reputation: 321

You show modify your Extra related_name on package ForeignKey.

models.py

class Extra(models.Model):
    extra = models.ForeignKey(Package,related_name='extra_related_name') #default for related_name would be 'extra_set'

You can access all extra fields via:

extras = list.extra_related_name.all()

Let's imagine you have only one extra existing on every Package model

views.py

def show_package(request):
    list = get_list_or_404(Package, ptype='sometype')
    list.extra = list.extra_related_name.all()[0]
    return render(request, 'table.html', {'list': list})

template

{% for row in list %}
<table class="provider_list">
 <tr>
    <td>{{ row.package_name}}</td>
    <td>{{ row.ptype }}</td>
    <td>{{ row.extra.data }}</td>
    <td>{{ row.extra.information }}</td>
 </tr>
</table>
{% endfor %}

If you are sure that there is at most one extra per package you should look at OneToOneField for easier access. If you are unsure, stick to ForeignKey and add checks in the view to check that you are accessing valid data.

Upvotes: 1

Related Questions