Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement get by: id, name, type and hp #8

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 19 additions & 3 deletions pokemon/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,28 @@
from pokemon.models import Pokemon, PokemonTypes


# TODO: Add a serializer for PokemonTypes, and use it as a nested serializer for PokemonSerializer
class TypeSerializer(serializers.ModelSerializer):
class Meta:
model = PokemonTypes
fields = ("type",)


class PokemonSerializer(serializers.ModelSerializer):
types = TypeSerializer(many=True)

class Meta:
model = Pokemon
fields = ('id', 'name_english', 'name_japanese', 'name_chinese', 'name_french', 'hp', 'attack', 'defense',
'special_attack', 'special_defense', 'speed', )
fields = (
"id",
"name_english",
"name_japanese",
"name_chinese",
"name_french",
"hp",
"attack",
"defense",
"special_attack",
"special_defense",
"speed",
"types",
)
83 changes: 70 additions & 13 deletions pokemon/views.py
Original file line number Diff line number Diff line change
@@ -1,55 +1,112 @@
from django.http import JsonResponse, HttpResponse
from django.http import Http404, JsonResponse
from django.shortcuts import get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from django.db.models import Q

from pokemon.models import Pokemon, VALID_POKEMON_TYPES
from pokemon.serializers import PokemonSerializer


@csrf_exempt
@api_view(['GET'])
@api_view(["GET"])
def pokemon_list(request):
"""
List all Pokemon
"""
pokemon = Pokemon.objects.all()
serializer = PokemonSerializer(pokemon, many=True)
return JsonResponse(serializer.data, safe=False, json_dumps_params={'ensure_ascii': False})
return JsonResponse(
serializer.data, safe=False, json_dumps_params={"ensure_ascii": False}
)


@csrf_exempt
@api_view(['GET'])
@api_view(["GET"])
def pokemon_by_id(request, id):
"""
Get Pokemon by ID
"""
# TODO: Implement Endpoint
return HttpResponse(status=501)
try:
pokemon = get_object_or_404(Pokemon, id=id)
serializer = PokemonSerializer(pokemon)
return JsonResponse(serializer.data, safe=False)
except Http404:
return JsonResponse({"error": "Not found"}, status=404)


@csrf_exempt
@api_view(['GET'])
@api_view(["GET"])
def pokemon_by_name(request, name):
"""
Get Pokemon by name
"""
# TODO: Implement Endpoint
return HttpResponse(status=501)
try:
pokemon = get_object_or_404(Pokemon, name_english__iexact=name)
serializer = PokemonSerializer(pokemon)
return JsonResponse(serializer.data, safe=False)
except Http404:
return JsonResponse({"error": "Not found"}, status=404)


@csrf_exempt
def pokemon_by_type(request, pokemon_type):
"""
Get Pokemon by type
"""
# TODO: Implement Endpoint
return HttpResponse(status=501)
try:
# check if type exists
if pokemon_type.lower() not in [t[0].lower() for t in VALID_POKEMON_TYPES]:
return JsonResponse({"error": "Bad request"}, status=400)

pokemon = Pokemon.objects.filter(types__type__iexact=pokemon_type)
serializer = PokemonSerializer(pokemon, many=True)
return JsonResponse(serializer.data, safe=False)
except Http404:
return JsonResponse({"error": "Not found"}, status=404)


@csrf_exempt
def pokemon_by_hp(request):
"""
Get Pokemon by HP
"""
# TODO: Implement Endpoint
return HttpResponse(status=501)

VALID_COMPARATORS = ["gt", "gte", "lt", "lte"]

try:
comparators = [
comparator
for comparator in VALID_COMPARATORS
if request.GET.get(comparator)
]

if not comparators:
return JsonResponse(
{"error": 'Invalid Operator. Must be one of ["gt","gte","lt","lte"]'},
status=400,
)

# Initialize the filter with Q objects based on the selected comparators
filter_query = Q()
for comparator in comparators:
value = int(request.GET.get(comparator))
if comparator == "gt":
filter_query &= Q(hp__gt=value)
elif comparator == "gte":
filter_query &= Q(hp__gte=value)
elif comparator == "lt":
filter_query &= Q(hp__lt=value)
elif comparator == "lte":
filter_query &= Q(hp__lte=value)

pokemons = Pokemon.objects.filter(filter_query)
serializer = PokemonSerializer(pokemons, many=True)

if pokemons.exists():
return JsonResponse(serializer.data, safe=False)
else:
return JsonResponse({"error": "Not found"}, status=404)

except Http404:
return JsonResponse({"error": "Not found"}, status=404)