如何根据先前的查询集结果进行过滤Django

时间:2019-02-18 15:47:43

标签: django django-views django-filter

目前,我有2个独立的查询集呈现在同一页面上,彼此独立。

Q1 = users

Q2 = f

Q1返回用户发布的半径(request.POST)内的所有用户。

Q2根据选择的过滤器(头发的颜色,年龄等)返回django_filters.FilterSetrequest.GET

Q2仅应过滤Q1的结果。我想将它们全部保留在同一页面上,而不是重定向到不同的URL。

如果有人可以解释这样做的最简单方法,我将不胜感激。

views.py

class ConnectView(View):
    template_name = 'connect/home.html'
    def get(self, request, *args, **kwargs):
        filter = ProfileFilter(request.GET.getlist('filter'))
        context = {
            'users': User.objects.exclude(username=request.user),
            'filter': filter
        }
        return render(request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        if 'latitude' in request.POST and 'longitude' in request.POST:
            try:
                location = Location(latitude=request.POST['latitude'], longitude=request.POST['longitude'], user = request.user)
                location.save()
            except:
                return JsonResponse({'message': 'location already stored!'})

        if 'radius' in request.POST:
            radius_km = request.POST.get('radius', 0)
            queryset = User.objects.annotate(
                radius_sqr=pow(models.F('loc__latitude') -
                request.user.loc.latitude, 2) + pow(models.F('loc__longitude') -
                request.user.loc.longitude, 2)
                ).filter(
                radius_sqr__lte=pow(int(radius_km) / 9, 2)
                ).exclude(username=request.user)
            filter = ProfileFilter(request.POST, queryset=queryset)
            messages.success(request, f'See the results of your search below.')
            return render(request, self.template_name)

        else:
            return render(request, self.template_name)

filters.py

class ProfileFilter(django_filters.FilterSet):
    class Meta:
        model = Profile
        fields = {
            'age': ['exact'],
            'interest': ['exact'],
        }

connecthome.html

  <form method="POST">
    {% csrf_token %}
    <h4>Enter a Distance.</h4>
    <input type="number" name="radius">
    {{ filter.form|crispy }}
    <button type="submit">Search.</button>
  </form>

    {% if filter %}
        {% for profile in filter %}
            <h5>{{ profile.user.first_name }}</h5>
            <p>{{ profile.age }}</p>
        {% empty %}
            <h1>No results, try again?</h1>
        {% endfor %}
    {% else %}
        {% for user in users %}
            <h5>{{ user.first_name }}</h5>
            <p>{{ user.profile.age }}</p>
        {% empty %}
            <h1>No results, try again?</h1>
        {% endfor %}
    {% endif %}

1 个答案:

答案 0 :(得分:1)

您应该将模板更改为仅包含POST半径和过滤器的一种形式。然后在发布方法中,使用位置/半径创建要传递给过滤器的查询集:

def post(self, request, *args, **kwargs):
    # default queryset, users is needed in context based on your get() method
    users = User.objects.exclude(username=request.user.username)
    queryset = Profile.objects.exclude(user=request.user)  
    if 'latitude' in request.POST and 'longitude' in request.POST:
        # code to store Location

    if 'radius' in request.POST:
        radius_km = request.POST.get('radius', 0)
        # reduce queryset by users within radius
        queryset = queryset.annotate(
            radius_sqr=pow(models.F('user__loc__latitude') -
            request.user.loc.latitude, 2) + pow(models.F('user__loc__longitude') -
            request.user.loc.longitude, 2)
            ).filter(
            radius_sqr__lte=pow(int(radius_km) / 9, 2)
            )
        messages.success(request, f'See the results of your search below.')

    filter = ProfileFilter(request.POST, queryset=queryset)
    return render(request, self.template_name, {'filter': filter, 'users': users})