检查列表中的类型django模板语言

时间:2013-09-01 00:18:50

标签: python django django-templates

我有列表有两种类型的元素让我们说元素是元素A或元素B.我将此列表从后端传递给模板。在模板中,我将为每个元素循环,然后我想检查它是否是类型A这样做,如果它是类型B那样做。我怎么做这种类型检查??

这里澄清一个非常简单的例子

Models.py
class Type_A(models.Model):
test1 = models.CharField()

class Type_B(models.Model):
test2 = models.CharField()


Views.py 
c = {}
l = list()
l = [Type_A.objects.all(), Type_B.objects.all()]
c['list'] = shuffle(l)
return render_to_response('test.html', c , context_instance=RequestContext(request) )

的test.html 我正在寻找像这样的东西

{% for x in list %}
    {% if x is Type_A %} 
       do this
    {% else %}
       do that
    {% endif %}
{% endfor %}

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

shuffle是一个就地操作(如sort),它没有返回值(它返回None)所以这个:

c['list'] = shuffle(l)

不能上班,c['list']将是None

>>> i = [1,2,3]
>>> b = [4,5,6]
>>> z
[1, 2, 3, 4, 5, 6]
>>> random.shuffle(z)  # Note, no return value
>>> z
[3, 6, 2, 1, 5, 4]  # z is shuffled

试试这个版本:

c = {}
type_a = [('A', x) for x in Type_A.objects.all()]
type_b = [('B', x) for x in Type_B.objects.all()]
combined = type_a+type_b
shuffle(combined)
c['random'] = combined

然后:

{% for t,i in random %}
   {% ifequal t "A" %}
      {{ i }} is Type "A"
   {% else %}
      {{ i }} is Type "B"
   {% endifequal %}
{% endfor %}

或者,你可以这样做:

{% for t,i in random %}
   {{ i }} is of type {{ t }}
{% endfor %}