0

我的列表有两种类型的元素,假设元素是元素 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 %}
4

2 回答 2

0

这就是模板过滤器的工作:

https://stackoverflow.com/a/12028864/1566605

https://docs.djangoproject.com/en/1.4/howto/custom-template-tags/#writing-custom-template-filters

于 2013-09-01T07:53:48.313 回答
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 %}
于 2013-09-01T08:40:36.380 回答