有没有办法在Django queryset中包含用户位置?

时间:2019-03-31 00:25:45

标签: javascript python geodjango

我正在尝试编写一个网站,以便用户搜索药品并返回附近有库存药品的药房列表。除了根据用户位置对结果进行排序以外,我大部分工作已经完成。

我已经弄清楚了如何从JS获取用户位置,但是我不知道如何将其传递回查询集。目前,我已经对其进行了设置,因此该脚本仅在经过身份验证时才在主页上运行,因为我是在强迫人们登录以使用该网站(为安全起见)。我尝试搜索示例,但实际上只提供了GeoIP

以下是相关代码:

home.html

    <form>
        <div class="input-group px-3">
          <input id="searchtxt" type="text" class="form-control" name="q" placeholder="Search for a medicine..." value="{{ request.GET.q }}">
          <div class="input-group-append">
            <button id='searchbtn' class="btn btn-warning btn-outline-dark" type="submit">Search</button>
          </div>
        </div>
    </form>

Under this I run through the resulting query_set object (locations) using the django template.

views.py

class StockListView(LoginRequiredMixin, ListView):
    model = Stock
    template_name = 'searcher/home.html'
    context_object_name = 'locations'

    def get_queryset(self):
        if self.request.GET.get('q'):
            drug_name = self.request.GET.get('q').split(' ')[0]

            queryset = Stock.objects.filter(Q(drug__nzulm__startswith=drug_name) & Q(stock__gt=0)).annotate(distance=Distance('pharmacy__location', location)).order_by('-distance', 'stock')
            # this is the point where I'm stuck, I'm not sure how to set "location" in the Distance().

            if queryset:
                return queryset
            else:
                messages.error(self.request, f'Sorry, no results for "{drug_name}".') # using Bootstrap messaging framework

及其正在搜索的模型:

class Stock(models.Model):
    drug = models.ForeignKey(Medicine, on_delete=models.CASCADE)
    pharmacy = models.ForeignKey(Pharmacy, on_delete=models.CASCADE)
    stock = models.IntegerField()

class Medicine(models.Model):
    nzulm = models.CharField(max_length=100)
    trade = models.CharField(max_length=100)
    strength = models.CharField(max_length=200, blank=True)
    formulation = models.CharField(max_length=50)

class Pharmacy(models.Model):
    owner = models.ForeignKey(User, on_delete=models.PROTECT)
    name = models.CharField(max_length=100)
    location = GIS.PointField()
    address = models.CharField(max_length=100, blank=True)
    suburb = models.CharField(max_length=100, blank=True)
    city = models.CharField(max_length=100, blank=True)

最后,这是我正在运行的用于获取JS中用户位置的代码。目前,它只是登录控制台,只是因为我不知道如何将其传回。

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        console.log("Geolocation is not supported by this browser.");
      }
    }

    function showPosition(position) {
      console.log("Latitude: " + position.coords.latitude +
      " Longitude: " + position.coords.longitude);
    }
    window.onload = getLocation();

当用户搜索药品时,我想以某种方式将其作为Point()对象包含在查询集中,以便可以首先以最短距离对查询集进行排序。

有人能指出我正确的方向吗?似乎我需要在此处包括AJAX,但是我不确定如何将其添加到GET方法中。任何帮助将不胜感激!

0 个答案:

没有答案