Reoraganized project
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class CountriesConfig(AppConfig):
|
||||
default_auto_field = "django.db.models.BigAutoField"
|
||||
name = "api.countries"
|
||||
@@ -0,0 +1,15 @@
|
||||
from django.db import models
|
||||
|
||||
|
||||
class Country(models.Model):
|
||||
name = models.CharField(max_length=100)
|
||||
alpha2 = models.CharField(max_length=2)
|
||||
alpha3 = models.CharField(max_length=3)
|
||||
region = models.CharField()
|
||||
|
||||
class Meta:
|
||||
db_table = "countries"
|
||||
managed = False
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
@@ -0,0 +1,9 @@
|
||||
from rest_framework import serializers
|
||||
|
||||
from api.countries.models import Country
|
||||
|
||||
|
||||
class CountrySerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Country
|
||||
fields = ["name", "alpha2", "alpha3", "region"]
|
||||
@@ -0,0 +1,12 @@
|
||||
from django.urls import path
|
||||
|
||||
import api.countries.views
|
||||
|
||||
urlpatterns = [
|
||||
path("", api.countries.views.CountryListView.as_view(), name="countries"),
|
||||
path(
|
||||
"/<str:alpha2>",
|
||||
api.countries.views.CountryByAlpha2View.as_view(),
|
||||
name="country_by_alpha2",
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,34 @@
|
||||
from django.conf import settings
|
||||
from rest_framework.exceptions import ValidationError
|
||||
from rest_framework.generics import ListAPIView, RetrieveAPIView
|
||||
|
||||
from api.countries.models import Country
|
||||
from api.countries.serializers import CountrySerializer
|
||||
|
||||
|
||||
class CountryListView(ListAPIView):
|
||||
queryset = Country.objects.all().order_by("alpha2")
|
||||
serializer_class = CountrySerializer
|
||||
|
||||
def filter_queryset(self, queryset):
|
||||
regions = self.request.query_params.get("region")
|
||||
if regions:
|
||||
regions_list = regions.split(",")
|
||||
invalid_regions = [
|
||||
region
|
||||
for region in regions_list
|
||||
if region not in settings.REGIONS
|
||||
]
|
||||
if invalid_regions:
|
||||
invalid_regions_str = ", ".join(invalid_regions)
|
||||
error_message = f"Invalid region(s): {invalid_regions_str}"
|
||||
raise ValidationError(error_message)
|
||||
|
||||
queryset = queryset.filter(region__in=regions_list)
|
||||
return queryset
|
||||
|
||||
|
||||
class CountryByAlpha2View(RetrieveAPIView):
|
||||
queryset = Country.objects.all()
|
||||
serializer_class = CountrySerializer
|
||||
lookup_field = "alpha2"
|
||||
Reference in New Issue
Block a user