简体   繁体   English

DRF,由模型选择字段查询集

[英]DRF, queryset by a models choices field

I have the following Django rest framework model:我有以下 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')
]

serializer:序列化器:

from rest_framework.serializers import Serializer
from .models import KnownLocation


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

I want to write a view with a query set ( maybe a get_queryset method will be better), where the query return all objects which has the same 'area' has the one past in by the user.我想写一个带有查询集的视图(也许 get_queryset 方法会更好),其中查询返回所有具有相同“区域”的对象,并且用户过去在其中。

in views.pyviews.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.pyurls.py

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

now for example, if you are using vue in front-end you can do the following:现在例如,如果您在前端使用 vue,您可以执行以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM