【发布时间】:2013-09-01 18:39:12
【问题描述】:
我是 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"}
}
]
这是我目前的实现(仅显示位置的实现):
在 models.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',
)
在 views.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')
我尝试了什么:我认为我不需要修改模型和序列化程序,因为它在调用上述域时适用于单个对象。所以我尝试在views.py 中实现一个LocationsViewSet 并在urls.py 中添加一个新的url,但我失败了。知道如何实施吗?也许只是在 LocationAPIView 中定义一个方法并更改定义一个类似这样的 url:
url(r'^all_locations/$', views.LocationAPIView.get_all_locations(), name='LocationAPIView')
提前致谢,如有任何帮助,我将不胜感激。
最好的问候, 迈克尔
【问题讨论】:
标签: python django json django-rest-framework