[英]DRF, queryset by a models choices field
我有以下 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 方法會更好),其中查詢返回所有具有相同“區域”的對象,並且用戶過去在其中。
在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)
在urls.py
path('KnownLocations/filter/area/<str:area>', views.filterArea_KnownLocation)
現在例如,如果您在前端使用 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.