开发者

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.


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 %}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜