首页 > 解决方案 > 如何在 django 中显示查询集中的直方图

问题描述

目标

通常,该应用程序会显示特定 Twitter 主题标签的位置数据。例如,如果用户输入“python”。该应用程序在 Twitter 中搜索包含主题标签“python”的最近推文,并在可能的情况下显示这些推文的位置数据。

目前,位置数据显示为 dict,这是通过Models.pydef display_locations(self)中的函数实现的。

现在,我试图在直方图上显示该数据。我已经在下面的Views.pydraw_histogram()中编写了函数,但我得到了下面所述的错误。我怀疑一个有效的解决方案可能是在函数中调用方法: ,但我不确定。Hashtag.display_locationsdraw_histogram()

我有两个备用问题:

  1. Views.pydraw_histogram()中,如何设置来达到目的?country_list
  2. 也许将draw_histogram()函数作为方法包含在class SearchResultsView(generic.ListView)? 如果是这样,我该怎么做?

错误

Exception Type: TypeError
Exception Value: draw_histogram() missing 1 required positional argument: 'self'

代码

模型.py

class Hashtag(models.Model):
    """ Model representing a specific Hashtag serch by user """
    search_text = models.CharField(max_length=140, primary_key=True)
    locations = models.ManyToManyField(Location, blank=True)

    def __str__(self):
        """ String for representing the Model object (search_text) """
        return self.search_text

    def display_locations(self):
        """ Creates a frequency dict of the locations attached to the Hashtag model """
        country_list = list(self.locations.values_list('country', flat=True).all())
        for country in country_list:
            location_freq = {i:country_list.count(i) for i in set(country_list)}
            return location_freq

视图.py

class SearchResultsView(generic.ListView):
    """ Generic class-based view listing search results of locations """
    model = Hashtag
    template_name = 'mapping_twitter/results.html'

    def get_queryset(self, **kwargs):
        """ Restrict the results to the search_text entered on the Form """
        form_input = self.request.GET.get('search_text')
        qs = Hashtag.objects.all().filter(search_text__iexact=form_input)
        return qs

    def get_context_data(self, **kwargs):
        context = super(SearchResultsView, self).get_context_data(**kwargs)
        context['search_text', 'locations'] = self.get_queryset()
        return context


def draw_histogram(request, self):
    """ Function to display a histogram of locations associated with the Hashtag """
    country_list = list(self.locations.values_list('country', flat=True).all())
    for country in country_list:
        location_freq = {i:country_list.count(i) for i in set(country_list)}
    plt.bar(list(country_freq.keys()), country_freq.values(), color='g')
    # redirect into the BytesIO object
    f = io.BytesIO()
    plt.savefig(f, format="png", facecolor=(0.95,0.95,0.95))
    plt.clf()
    # Add the contents of the BytesIO object to the response and return
    return HttpResponse(f.getvalue(), content_type="image/png")

标签: pythondjangomatplotlibdjango-views

解决方案


推荐阅读