DRF, набор запросов по полю выбора моделей - PullRequest
0 голосов
/ 28 февраля 2020

У меня есть следующая Django модель остального фреймворка:

from django.db import models

from django.utils import timezone

from Project_Level.CONSTANTS import AREAS


class KnownLocation(models.Model):
    name = models.CharField(name="Name",
                            unique=False,
                            max_length=150,
                            blank=False,
                            help_text="Enter the name of the location's name")

    area = models.CharField(name='Area',
                            max_length=8,
                            choices=AREAS)

    date_added = models.DateTimeField(default=timezone.now)

    latitude = models.FloatField(name="Latitude",
                                 unique=True, max_length=255, blank=False,
                                 help_text="Enter the location's Latitude, first when extracting from Google Maps.",
                                 default=1)

    longitude = models.FloatField(name="Longitude",
                                  unique=True, max_length=255, blank=False,
                                  help_text="Enter the location's Longitude, second when extracting from Google Maps.",
                                  default=1)
AREAS = [
    ('210', '210'),
    ('769', '769'),
    ('300', '300')
]

сериализатор:

from rest_framework.serializers import Serializer
from .models import KnownLocation


class KnownLocationSerializer(Serializer):
    class Meta:
        model = KnownLocation
        fields = ('id', 'Name', 'Area', 'Latitude', 'Longitude')

Я хочу написать представление с набором запросов (возможно, метод get_queryset будет лучше), где запрос возвращает все объекты, которые имеют одинаковую «область», в которой пользователь вставил.

1 Ответ

0 голосов
/ 29 февраля 2020
Например,

in views.py

> @api_views (['GET']) def filterArea_KnownLocation(request, area):
>     locations = KnownLocation.objects.filter(area=area)
>     serializer = KnownLocationSerializer(locations, many=True, context={'request': request})
>     return Response(serializer.data, status=status.HTTP_200_OK)

in urls.py

path('KnownLocations/filter/area/<str:area>', views.filterArea_KnownLocation)

. Если вы используете vue в front-end, вы можете сделать следующее:

getLocationsByArea(){
  this.$http
      .get("/KnownLocations/filter/area/210", {
        headers: {
          "Content-Type": "application/json",
        }
      })
      .then((res)=>{
        this.locations = res.data;
      });
...