我有一个包含ForeignKey的模型。我正在尝试序列化此模型,并希望控制外键字段返回的字段。见下文:
models.py
class Surveyor(models.Model):
num = models.CharField(max_length=3)
name = models.CharField(max_length=250)
class Anblsrecord(models.Model):
...
sur_num = models.ForeignKey(Surveyor, on_delete=models.CASCADE)
views.py
def anbls_points(request):
points_as_geojson = serialize('geojson', Anblsrecord.objects.all()[:5], fields=(... 'sur_num'))
return JsonResponse(json.loads(points_as_geojson))
当我查看此内容时,我得到: ...“ sur_num”:1 ... 其中Surveyor类中的“ 1”是“ num”。我想返回“名称”。
我看过https://docs.djangoproject.com/en/2.2/topics/serialization/,它讨论了多表继承,但是找不到相关表的任何内容。
任何帮助将不胜感激。
答案 0 :(得分:1)
带有django-rest-framework-gis的Django Rest Framework序列化程序起作用了:
from anblsrecords import models
from rest_framework_gis.serializers import GeoFeatureModelSerializer
class AnblsrecordSerializer(GeoFeatureModelSerializer):
sur_name = serializers.CharField(source='sur_num.name')
class Meta:
model = models.Anblsrecord
geo_field = "geom"
fields = (
...
'sur_name',
)
from rest_framework import generics
class ListAnbls_points(generics.ListCreateAPIView):
queryset = Anblsrecord.objects.all()[:5]
serializer_class = serializers.AnblsrecordSerializer
这将返回: “属性”:{ ..., “ sur_name”:“测量员的姓名”,...},并包括几何特征。