2013-10-22 79 views
0

在我的模板中,我想用不同表格中的for循環顯示我的模型的所有字段。每個表格都有不同數量的字段。我唯一知道的就是領域的順序。在不同表格中顯示錶格字段

我的模型:

class Act(models.Model): 
    #table_1 
    my_field=models.IntegerField(max_length=4, blank=False, null=False) 
    bar=models.IntegerField(max_length=2, blank=False, null=False) 
    ... 

    #table_2 
    test=models.CharField(max_length=2, blank=True, null=True, default=None) 
    my_new_field=models.CharField(max_length=2, blank=True, null=True, default=None) 
    blabla=models.CharField(max_length=2, blank=True, null=True, default=None) 
    ... 

    #table_3 
    foo=models.IntegerField(max_length=2, blank=False, null=False) 
    ... 

我的模板:

<table id="table_1"> 
    <!-- display my_field and bar --> 
    {% for field in form %} 
    {% endfor %} 
</table> 

<table id="table_2"> 
    <!-- display test, my_new_field and blabla --> 
    {% for field in form %} 
    {% endfor %} 
</table> 

<table id="table_3"> 
    <!-- display foo --> 
    {% for field in form %} 
    {% endfor %} 
</table> 

這可能嗎?

+0

你可以使用form.fieldname和form.fieldname每次手動輸入它的東西 – Anto

+0

如果有數百個字段呢? – rom

+1

你會在你的模板中使用數百個字段,還有其他方式可以使用三種不同的模型通過外鍵連接 – Anto

回答

0

感謝Anto Vinish,我找到了一個可以接受的解決方案:使用slice

<table id="table_1"> 
    <!-- display my_field and bar --> 
    {% for field in form|slice:":10" %} 
    {% endfor %} 
</table> 

<table id="table_2"> 
    <!-- display test, my_new_field and blabla --> 
    {% for field in form|slice:"10:25" %} 
    {% endfor %} 
</table> 

<table id="table_3"> 
    <!-- display foo --> 
    {% for field in form|slice:"25:" %} 
    {% endfor %} 
</table> 

你要算對,如果你在你的模型中添加字段更新的數字,但至少你沒有別的改變。沒有額外的模型,沒有額外的代碼,所以沒有額外的查詢

解決!