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

时间:2020-02-28 19:09:41

标签: python django django-rest-framework

我有以下Django rest框架模型:

RMSE
reg = GridSearchCV(estimator=xgb_model,  
                   scoring=make_scorer(mean_squared_error, squared=False),
                   param_grid= {'max_depth': [2], 'n_estimators': [50]}, 
                   cv=folds,
                   verbose=False)

reg.fit(X, y)
reg.best_score_
4.618242594168436

序列化器:

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)

我想编写一个带有查询集的视图(也许使用get_queryset方法会更好),其中查询返回所有具有相同“区域”的对象已被用户过去的对象。

1 个答案:

答案 0 :(得分:0)

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;
      });
相关问题