Spatial Digger
Spatial Digger

Reputation: 1993

Django passing a value through a ListView

I have the listview working, and I tested a def in the shell, so now I'm tring to pass the returned result from the def through the listview so I can display the value in the html. So the problem is, how to do this?

Here is the def, it is passing some raw sql which compares two tables in two different schemas to show the user how many records need updating.

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

And here is the functioning listview

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

Do I add the following? If so how do I access the data on the html side?

    data = count_new_rows()

Upvotes: 0

Views: 195

Answers (1)

bogeymin
bogeymin

Reputation: 685

I think you are probably are looking for 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

Then in a your template, you can do something like:

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

Upvotes: 2

Related Questions