i have a django installation with currently two apps ( common / destinations ) and i want to create custom api views across these apps.
in common i have a model country
models.py app common
from django.db import models
# Create your models here.
class Country(models.Model):
CONTINENTS = (
('Europe', 'Europe'),
('Asia', 'Asia'),
('Africa', 'Africa'),
('northamerica', 'North America'),
('southamerica', 'South America'),
('australia', 'Australia')
)
name = models.CharField(max_length=120)
code = models.CharField(max_length=2)
continent = models.CharField(max_length=11, choices=CONTINENTS)
content = models.TextField()
image = models.FileField()
models.py app destination
from django.db import models
# Create your models here.
class Destination(models.Model):
name = models.CharField(max_length=120)
code = models.CharField(max_length=3)
country = models.ForeignKey("common.Country", on_delete=models.CASCADE)
image = models.FileField()
serializers.py app destination
from rest_framework import serializers
from common.serializers import CountrySerializer
from .models import Destination
class DestinationSerializer(serializers.ModelSerializer):
country = CountrySerializer()
class Meta:
model = Destination
fields = ("id", "name", "code", "country", "image")
views.py app destination
from rest_framework import views
from rest_framework.response import Response
from .serializers import DestinationSerializer, ImageSerializer
from .models import Destination
# Create your views here.
class DestinationView(views.APIView):
def get(self, request, code):
destination = Destination.objects.filter(code=code.upper())
if destination:
serializer = DestinationSerializer(destination, many=True)
return Response(status=200, data=serializer.data)
return Response(status=400, data={"Destination not found"})
When i make a API call /api/destination/PMI everything works. i get my destination from destination app and country from common app.
**GET /api/destination/**
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"id": 1,
"name": "Palma de Mallorca",
"code": "PMI",
"country": {
"id": 1,
"name": "Spain",
"code": "ES",
"continent": "Europe",
"content": "Lorem Ipsum",
"image": "http://localhost:1000/media/logo.svg"
},
"image": "http://localhost:1000/media/2020-08-03_07-40.png"
}
]
Now i want to create a view which only returns the images from common / destination
e.g.
GET **/api/destination/pmi/image**
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"code": "pmi",
"destination_image" : "image.png",
"country_image" : "country.png"
}
]
how, if possible, can i achieve that?