I am new to the Django framework and the Django REST framework, but I got the basic setup and implementation. It works like a charm when I call a domain for individual objects, for example. http://mydomain.com/location/1 (where 1 is the primary key). This gives me a JSON response like:
{"id": 1, "location": "Berlin", "country": 2}
.. and http://mydomain.com/country/2 answers like:
{"id": 2, "country": "Germany"}
What I need: Now I need to get several locations, for example. when calling the domain http://mydomain.com/all_locations/ . I would expect an answer like:
[ {"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} ]
This is optional:. In the second step, I would like to have several countries and locations in one answer when I call http://mydomain.com/mix_all_locations_countries/ , for example:
[ {"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"} } ]
Here's my implementation so far (only showing the location implementation):
in models.py :
class Location(models.Model):
in serializers.py :
class LocationsSerializer(serializers.ModelSerializer): country_id = serializers.Field(source='country.id') class Meta: model = Location fields = ( 'id', 'location', 'country_id', )
in views.py :
class LocationAPIView(generics.RetrieveAPIView): queryset = Location.objects.all() serializer_class = LocationSerializer
in urls.py :
url(r'^location/(?P<pk>[0-9]+)/$', views.LocationAPIView.as_view(), name='LocationAPIView')
What I tried: I think I do not need to change the model and serializer, because it works for single objects when calling the domain mentioned above. So I tried to implement LocationsViewSet in views.py and added a new url in urls.py but I failed. Any idea how I could implement it? Maybe just define a method in LocationAPIView and change the url definition similar to this:
url(r'^all_locations/$', views.LocationAPIView.get_all_locations(), name='LocationAPIView')
Thanks in advance, I will appreciate any help.
Regards, Michael