Python 我必须显示';地点';与';纬度';和';经度';。已在控制台中打印所需位置,但未保存
我尝试了很多方法,包括SerializerMethodField,但都没有成功。 我想打印结果中与模型的纬度和经度相关的位置 Models.pyPython 我必须显示';地点';与';纬度';和';经度';。已在控制台中打印所需位置,但未保存,python,django,rest,Python,Django,Rest,我尝试了很多方法,包括SerializerMethodField,但都没有成功。 我想打印结果中与模型的纬度和经度相关的位置 Models.py class CustomerProfile(models.Model): location = models.PointField(default=Point(0,0),geography=True) latitude = models.DecimalField(blank=True,max_digits=9,decimal_place
class CustomerProfile(models.Model):
location = models.PointField(default=Point(0,0),geography=True)
latitude = models.DecimalField(blank=True,max_digits=9,decimal_places=6,default=None,null=True)
longitude = models.DecimalField(blank=True,max_digits=9,decimal_places=6,default=None,null=True)
序列化程序.py
class CustomerSerializer(serializers.ModelSerializer):
class Meta:
model = CustomerProfile
fields = "__all__"
Views.py
from django.contrib.gis.geos import GEOSGeometry
class CustomerView(APIView):
def get(self, request, format=None):
query = CustomerProfile.objects.all()
serializer = CustomerSerializer(query, many=True)
return Response(serializer.data)
def post(self, request,data,format=None):
serializer = CustomerSerializer(data=request.data)
if serializer.is_valid():
lat=getattr(data,"latitude")
lon= getattr(data,"longitude")
lat_1 = float(str(lat))
lon_1 = float(str(lon))
print(lon_1)
if lat_1 and lon_1:
location = Point((lat_1, lon_1), srid=4326)
print(location)
if location:
loc=getattr(data,"location")
print(loc)
loc=location
Serializer.save()
return Response({"message":"Customer Profile Updated Successfully","data":serializer.data}, status=200)
return Response({"message":"Customer registration failed!!","data":serializer.data}, status=400)
如果我理解正确,
print(location)
是您要保存的,并且print(loc)
也在表单中,但您实际上不想使用它,因为您已经有了lat和long分隔,对吗
我发现您的代码中存在两个问题:
loc=location
无法按预期工作。loc将首先是data.location,然后是新值,但它不会将data.location设置为新值。我不确定它是否有效,但您可以尝试如下操作:setattr(数据,“位置”,位置)
因此设置新值
另一个是Serializer.save()
,它是大写的,在python中,大写很重要:Serializer.save()
。
简要说明:您应该使用一个linter直接检查语法和变量名。它应该向您显示此变量未设置。PyCharm是使用python的优秀编辑器
我认为可以像这样将变量传递给save方法:
serializer.save(位置=位置)