2013-12-20 2 views
1

У меня есть следующий код:Django шаблон фильтра динамически модели поля

# main.html 

<div class="ingest"> 
    {% includes "checklist.html" with is_ingest=1 %} 
</div> 

<div class="master"> 
    {% includes "checklist.html" with is_master=1 %} 
</div> 

-

# checklist.html 

{% if is_ingest %} 
    {% for option in checklist_options %} 
     {% if option.is_ingest %} 
      do something 
     {% endif %} 
    {% endfor %} 
{% endif %} 

{% if is_master %} 
    {% for option in checklist_options %} 
     {% if option.is_master %} 
      do something 
     {% endif %} 
    {% endfor %} 
{% endif %} 

Есть ли способ, чтобы упростить код, так что я могу передать переменную как:

{% for option in checklist_options %} 
     {% if option.*VARIABLE* %} 
      do something 
     {% endif %} 
    {% endfor %} 

Как я могу это сделать, поэтому мне не нужно многократно повторять себя? (В фактическом коде я должен повторить описанную выше схему 5 раз.)

+0

Думаю, вам следует решить проблему в стороне зрения. пожалуйста, покажите мой пример вашего взгляда и моделей. Возможно, вы можете сделать какой-то запрос и избегать некоторых '' '' '' '' '' '' '' '' '' '' '' '' '' – lalo

ответ

1

Ну, я думаю, вы можете решить эту проблему в поле зрения. Я не знаю, ваши взгляды, но я приведу пример:

def checklist_options(request): 
    # I dont know how you get your query 
    checklist_options = CheckOption.objects.all() 

    #I dont know where it comes from 
    is_master = True 
    if is_master: 
     masters_checklist_options = checklist_options.filter(is_master=True) 

    #I dont know where it comes from 
    is_ingest = True 
    if is_ingest: 
     ingest_checklist_options = checklist_options.filter(is_ingest=True) 

    return render(request, ' main.html', { 
     "masters_checklist_options": masters_checklist_options 
     "ingest_checklist_options": ingest_checklist_options 
    },) 

Таким образом, ваш main.html может быть:

<div class="ingest"> 
    {% includes "checklist.html" with collection=ingest_checklist_options %} 
</div> 

<div class="master"> 
    {% includes "checklist.html" with collection=master_checklist_options %} 
</div> 

и checklist.html:

{% for option in collection %} 
    do something 
{% endfor %} 

Что вас выиграть?

Вы можете указать свой логин во взглядах (возможно, это должно быть в моделях).

Вы избегаете проблемы с n + 1, когда вы вызываете {% if option.is_master %}, в качестве примера. Потому что в каждом рендеринге check_list.html у вас уже есть фильтр is_master или is_ingest.

Надеюсь, вы не поняли мою точку зрения, я догадался, что вы модели, и дайте вам пример с дураком. Если вам нужна помощь, покажите нам свой вид и модели, и я буду в состоянии помочь вам больше.

Надежда помогает

Смежные вопросы