我正在开发基于Web的应用程序,该应用程序实现以下内容:
在数据库中
person(personid, fullname, cityid)
city(cityid, cityname, countryid)
country(countryid, countryname)
在SERIALIZER中
class CountrySerializer(serializers.Serializer):
id=serializers.IntegerField()
name=serializers.CharField()
class CitySerializer(serializers.Serializer):
id=IntegerField()
name=CharField()
country=CountrySerializer()
class PersonSerializer(serializers.Serializer):
id=IntegerField()
person=CharField()
city=CitySerializer()
在API视图中
from .custom_utils import raw_sql_select
class APIView_Person(generics.GenericAPIView):
serializer_class = PersonSerializer
permission_classes = (IsAuthenticatedOrReadOnly,)
def get_queryset(self):
query=("""
SELECT
p.personid as id,
p.fullname as person,
json_build_object(
'id',ct.cityid,
'name',ct.cityname,
'country',json_build_object(
'id',cntry.countryid,
'name',cntry.countryname
)
) AS city
FROM persons p
JOIN city ct ON ct.cityid=p.cityid
JOIN country cntry ON cntry.countryid=ct.countryid
""")
return raw_sql_select(query, "db_connection")
def get(self, request):
rows = [
{
"id": col.id,
"person": col.person,
"city": col.city
} for col in self.get_queryset()[1]
]
results = PersonSerializer(rows, many=True).data
return Response(results or [])
前沿
const [state, setState] = useState({
personList: []
})
useEffect(()=>{
fetch('/api/persons/', {method: 'GET', headers:{'Content-Type':'application/json'}})
.then(res=>res.json())
.then(rows=>setState(states=>({...states,personList:rows})))
}, [])
return(
<>
<Typography variant="body1" component="p">{state.person}</Typography>
<Typography variant="caption" component="p" color="textSecondary">{state.city}, {state.city.country}
</Typography>
</>
)
这是我目前设计API的方式。
我的问题是: