我正在使用 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."
}
我在这里错过了什么。
原文由 Melissa Stewart 发布,翻译遵循 CC BY-SA 4.0 许可协议
Method not allowed
错误是因为它在您的 API 类中搜索get()
方法,但找不到。API类的一般格式如下
如果你想在某个时候调用
get_or_create()
方法,你可以像任何其他方法一样进行,