【发布时间】:2018-08-22 10:49:11
【问题描述】:
我正在使用 django.rest_framework。我有一个特定视图的 get_or_create 方法,
class LocationView(views.APIView):
def get_or_create(self, request):
try:
location = Location.objects.get(country=request.data.get("country"), city=request.data.get("city"))
Response(location, status=status.HTTP_200_OK)
except Location.DoesNotExist:
serializer = LocationSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
这是位置模型,
class Location(models.Model):
country = models.CharField(max_length=255)
city = models.CharField(max_length=255, unique=True)
latitude = models.CharField(max_length=255)
longitude = models.CharField(max_length=255)
class Meta:
unique_together = ('country', 'city')
这是我的网址,
url(r'^location/$', LocationView.as_view(), name='location'),
当我通过以下方式调用此端点时, http://127.0.0.1:8000/api/v1/bouncer/location/?country=USA&&city=Sunnyvale&&latitude=122.0363&&longitude=37.3688
这就是我得到的,
{
"detail": "Method \"GET\" not allowed."
}
我在这里错过了什么。
【问题讨论】:
-
将
get_or_create()更改为get() -
但我需要get_or_create,它有不同的用途。
-
由于 url 中的双斜杠(由 postman 环境变量引起),我遇到了这个错误。例如
api.example.com/v1//accounts也可能导致此错误。通过删除额外的斜线轻松修复
标签: python django python-3.x django-rest-framework