如何检查django_tables2对象为空/ null?

时间:2016-08-17 17:47:40

标签: python django

我想解决的问题:
仅当表my_table不为空时才显示搜索栏,否则,将其隐藏。

这是我的views.py:

def my_table(request):
    model1 = Model1.objects.all().filter(Q(some_query))
    table = MyTable(model1)
    RequestConfig(request).configure(table)
    if not table:
        print "table is empty"
        table = None
    else:
        print "table is not empty."
    return render(request, 'my_table.html', {'my_table':table,})

这是我的my_table.html

{% load render_table from django_tables2 %}
{% if my_table  %}
Number of entries: {{ my_table|length }}.
<section>
    <form method="post" action=".">
      {% csrf_token %}
      <input type="text" class="search-query span80" id="search" name="search" placeholder="Type to search">
      <button type="submit" class="btn">Search</button> 
    </form>
</section>
{% else %}
<!-- There's no my_table. -->
{% endif%}

{% render_table my_table %}

但是,my_table(request) views.py中的这个表对象实际上什么也没有,它不会在html中呈现任何内容,但它不是空的,并显示搜索栏。
请指教。我做错了什么?

回应评论,这是MyTable代码:

class MyTable(tables.Table):
    entry1 = tables.Column(verbose_name="Entry 1")
    entry2 = tables.Column(verbose_name="Entry 2")
    class Meta:
        model = MyModel
        empty_text = "There is no entry record."
        order_by = "entry1"
        orderable = True
        sequence = ('entry1', 'entry2')
        fields = ('entry1', 'entry2')
        attrs = {"class": "paleblue", "style": "width:380px"}

这是MyModel的代码:

class MyModel(models.Model):
    entry1 = models.CharField(primary_key=True, max_length=11L, db_column='Entry1', blank=True) # Field name made lowercase.
    entry2 = models.CharField(max_length=11L, db_column='Entry2', blank=True) # Field name made lowercase.
class Meta:
    db_table = 'my_table'

1 个答案:

答案 0 :(得分:2)

在views.py中,您可以使用:

if table.data.data.__len__ > 0:

在您的模板中,您可以使用:

{% if table.data|length > 0 %}
do whatever you want here...
{% endif %}