Django通过ListView传递值

时间:2019-03-02 22:21:20

标签: django listview

我有一个listview,并且我在shell中测试了一个def,所以现在我正尝试将def的返回结果通过listview传递,这样我就可以在html中显示值了。那么问题是,该怎么做?

这是def,它传递了一些原始sql,该sql比较了两种不同模式中的两个表,以向用户显示需要更新多少记录。

def count_new_rows():
    with connection.cursor() as cursor:
        cursor.execute("""
        SELECT count(*)
        FROM samples.samples a
        FULL OUTER JOIN kap.sample b
        ON a.area_easting = b.area_easting AND a.area_northing = b.area_northing AND a.sample_number = b.sample_number AND a.context_number = b.context_number
        WHERE
        (a.area_easting IS  NULL AND a.area_northing IS  NULL AND a.sample_number IS   NULL AND a.context_number IS  NULL)
        OR
        (b.area_easting IS  NULL AND b.area_northing IS  NULL AND b.sample_number IS  NULL AND b.context_number IS  NULL)
        """)
        count = cursor.fetchall()

        return count

这是起作用的列表视图

class SampleListView(generic.ListView):
    template_name = 'sample/sample_list.html'
    model = Sample
    paginate_by = 50
    queryset = Sample.objects.filter(sample_type='Organic')

我是否添加以下内容?如果是这样,我如何访问html端的data

    data = count_new_rows()

1 个答案:

答案 0 :(得分:2)

我认为您可能正在寻找get_context_data()

https://docs.djangoproject.com/en/2.1/ref/class-based-views/mixins-simple/#django.views.generic.base.ContextMixin.get_context_data

def get_context_data(**kwargs):
    context = super().get_context_data(**kwargs)

    context['new_rows'] = count_new_rows()

    return context

然后在您的模板中,您可以执行以下操作:

<div>
     <b>New Rows:</b> {{ new_rows }}
</div>