I need help with this error that I am being presented with and it is the following. I have a database that when I perform the query has a list of points throughout the city, these points are in latitude and longitude format separately, now I need to pass them to geodjango and I need to serialize the data to convert it into geojson but I can't find the way to find the solution, I have the data like this from the database:
{'type': 'Feature', 'properties': {'name': 'Centro Puerto Lopez', 'direction': 'Calle 5 # 7-28', 'latitude': '4.08467', 'longitude': '-72.9558', 'city': 'Puerto Lopez', 'department': 'Meta', 'pk': '97'}, 'geometry': None}, {'type': 'Feature', 'properties': {'name': 'Bachue Acacias', 'direction': 'Carrera 35 # 14-23', 'latitude': '3.98454', 'longitude': '-73.777', 'city': 'Acacias', 'department': 'Meta', 'pk': '98'}, 'geometry': None}, {'type': 'Feature', 'properties': {'name': 'Ciudad Porfia', 'direction': 'Carrera 43 # 67-04 Sur', 'latitude': '4.07094', 'longitude': '-73.6695', 'city': 'Villavicencio', 'department': 'Meta', 'pk': '99'}, 'geometry': None}, {'type': 'Feature', 'properties': {'name': 'Ciudad Milenio', 'direction': 'Calle 53 S # 33 - 02', 'latitude': '4.08341', 'longitude': '-73.6645', 'city': 'Villavicencio', 'department': 'Meta', 'pk': '100'}, 'geometry': None}]}
The data is displayed, I am trying to serialize it like this:
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.views.generic import ListView, CreateView, UpdateView, DeleteView, TemplateView
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.core.serializers import serialize
import json
from apps.pdv.models import Pdv, Market
from apps.pdv.forms import PdvForm
# Create your views here.
# Clase para listar los pdv
class baseView(TemplateView):
template_name = "base/maps_base.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
market = Pdv.objects.all()
# for mark in market:
# print(mark)
context["markers"] = json.loads(serialize("geojson", Market.objects.all()))
context["markers_"] = json.loads(serialize("geojson", Pdv.objects.all()))
# print(context["markers"])
print(context["markers_"])
return context
but the data that the serialization returns is like this, clearly it is not understanding how to pass latitude and longitude to it so that it can be converted into a point.
{'type': 'Feature', 'properties': {'name': 'Ciudad Porfia', 'direction': 'Carrera 43 # 67-04 Sur', 'latitude': '4.07094', 'longitude': '-73.6695', 'city': 'Villavicencio', 'department': 'Meta', 'pk': '99'}, 'geometry': None}, {'type': 'Feature', 'properties': {'name': 'Ciudad Milenio', 'direction': 'Calle 53 S # 33 - 02', 'latitude': '4.08341', 'longitude': '-73.6645', 'city': 'Villavicencio', 'department': 'Meta', 'pk': '100'}, 'geometry': None}]}
I forgot to comment on a code snippet of the model
class Pdv(models.Model):
name = models.CharField(max_length=150, unique=True, verbose_name="Nombre del PDV")
direction = models.CharField(max_length=200, verbose_name="Dirección")
latitude = models.FloatField(verbose_name="Latitud")
longitude = models.FloatField(verbose_name="Longitud")
# latitude = models.CharField(max_length=100, verbose_name="Latitud")
# longitude = models.CharField(max_length=100, verbose_name="Longitud")
city = models.CharField(max_length=50, verbose_name='Ciudad')
department = models.CharField(max_length=50, verbose_name='Departamento')
# We create the str that returns us when the class is called
def __str__(self):
# self.datos = [self.name, self.direction, self.latitude, self.longitude, self.city, self.department]
return self.name
# Funcion para convertir todos los campos a json y ser devueltos a la vista
def toJson(self):
item = model_to_dict(self)
return item
# They are changes that I can make to impact the db and registry of the django admin
class Meta:
verbose_name = "Pdv"
verbose_name_plural = "Pdvs"
db_table = "pdv"
They ask me that the user can enter the coordinates by means of an input in float. I can't put a point because it turns me into a map and they don't want it that way, they have to receive them as text.
How else can you guide me in this way to guide me more?
I hope you can better guide me to solve my error, I thank you from the bottom of my heart for the help.
Have a look at this (if you didn't already): https://docs.djangoproject.com/en/1.11/ref/contrib/gis/serializers/
It's not really that the serializer doesn't understand your data, your data is simply not formatted in an ideal way, why don't you already output it with a geometry object that contains the proper coordinates: [lat, lng]
?
Your GeoJSON objects would ideally look something like this:
{
"type": "Feature",
"properties": {
"name": "Centro Puerto Lopez",
"direction": "Calle 5 # 7-28",
"latitude": "4.08467",
"longitude": "-72.9558",
"city": "Puerto Lopez",
"department": "Meta",
"pk": "97"
},
"geometry": {
"type": "Point",
"coordinates": [-72.9558, 4.08467]
}
}
So you could try something like this (note the new import!):
from django.contrib.gis.geos import Point
class Pdv(models.Model):
name = models.CharField(max_length=150, unique=True, verbose_name="Nombre del PDV")
direction = models.CharField(max_length=200, verbose_name="Dirección")
latitude = models.FloatField(verbose_name="Latitud")
longitude = models.FloatField(verbose_name="Longitud")
city = models.CharField(max_length=50, verbose_name='Ciudad')
department = models.CharField(max_length=50, verbose_name='Departamento')
location = Point(longitude, latitude)
and then you might be able to do something like this later on when serializing:
context["markers_"] = json.loads(serialize("geojson", Pdv.objects.all(), geometry_field='location'))
don't know if that would work though...