我是 Django 框架和 Django REST 框架的新手,但我已经运行了基本的设置和实现。当我为单个对象调用域时,它就像一个魅力,例如http://mydomain.com/location/1(其中 1 是主键)。这给了我这样的 JSON 响应:
{"id": 1, "location": "Berlin", "country": 2}
.. 和http://mydomain.com/country/2响应如下:
{"id": 2, "country": "Germany"}
我需要什么: 现在我需要获取多个位置,例如在调用域http://mydomain.com/all_locations/时。我希望得到这样的回应:
[
{"id": 1, "location": "Berlin", "country": 2},
{"id": 2, "location": "New York", "country": 4},
{"id": 3, "location": "Barcelona", "country": 5},
{"id": 4, "location": "Moscow", "country": 7}
]
这是可选的:在第二步中,当我调用http://mydomain.com/mix_all_locations_countries/时,我希望在一个响应中包含多个国家和地区,例如:
[
{"locations":
{"id": 1, "location": "Berlin", "country": 2},
{"id": 2, "location": "New York", "country": 4},
{"id": 3, "location": "Barcelona", "country": 5},
{"id": 4, "location": "Moscow", "country": 7}
},
{"countries":
{"id": 1, "country": "Brazil"}
{"id": 2, "country": "Germany"},
{"id": 3, "country": "Portugual"}
{"id": 4, "country": "USA"},
{"id": 5, "country": "Spain"},
{"id": 6, "country": "Italy"}
{"id": 7, "country": "Russia"}
}
]
到目前为止,这是我的实现(仅显示位置的实现):
在模型.py中:
class Location(models.Model):
# variable id and pk are always available
location = models.CharField(max_length=100)
country = models.ForeignKey("Country")
在serializers.py中:
class LocationsSerializer(serializers.ModelSerializer):
country_id = serializers.Field(source='country.id')
class Meta:
model = Location
fields = (
'id',
'location',
'country_id',
)
在view.py中:
class LocationAPIView(generics.RetrieveAPIView):
queryset = Location.objects.all()
serializer_class = LocationSerializer
在urls.py中:
url(r'^location/(?P<pk>[0-9]+)/$', views.LocationAPIView.as_view(), name='LocationAPIView')
我尝试了什么:我认为我不需要修改模型和序列化程序,因为它在调用上述域时适用于单个对象。所以我尝试实现一个LocationsViewSet
inviews.py
并添加一个新的 url in urls.py
,但我失败了。知道如何实施吗?也许只是在 LocationAPIView 中定义一个方法并更改定义一个类似于这样的 url:
url(r'^all_locations/$', views.LocationAPIView.get_all_locations(), name='LocationAPIView')
在此先感谢,我将不胜感激。
最好的问候,迈克尔