Serialize sqlite query to geojson geodjango rest framework gis query

110 views Asked by At

Friends, help me with this problem that is being presented to me and it is the following: -I have a database (sqlite) where I store point information, these points are stored like this:

The data was requested so that it can be stored in this way and later carry out the serialization, this in order to control writing errors of the points and they are correctly referenced.

Model.py

````
from django.db import models
from django.forms import model_to_dict

# Create your models here.

class Point(models.Model):
    name = models.CharField(max_length=150, unique=True, verbose_name="Name")
    direction = models.CharField(max_length=200, verbose_name="Direction")
    latitude = models.FloatField(verbose_name="Latitude")
    longitude = models.FloatField(verbose_name="Longitude")

     # 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

    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 = "Point"
        verbose_name_plural = "Points"
        db_table = "Point"
```

I tried to convert the query into geojson but I'm new, don't force me to find documentation that better explains how to use the rest-framework-gis serializer, I hope I'm doing it correctly and if not, I hope you can help me

  • Create a serializer to try to convert the query into a geojson, like so: Serializers.py

    from django.contrib.gis.geos import Point
    from rest_framework_gis import serializers
    from rest_framework_gis.serializers import GeometrySerializerMethodField
    from .models import *
    
    class MarketSerializer(serializers.GeoFeatureModelSerializer):
    
        other_point = GeometrySerializerMethodField()
    
        def get_other_point(self, obj):
            return Point(obj.latitude, obj.longitude)
    
        class Meta:
            model = Point
            geo_field = 'other_point'
    
  • From the view of create a url like this:

    from django.views.generic import TemplateView
    from django.core.serializers import serialize
    
    from rest_framework import viewsets
    from rest_framework_gis import filters
    
    from apps.point.serializers import MarketSerializer
    
    from apps.point.models import *
    
    # Create your views here.
    
    class baseView(TemplateView):
        template_name = "base/maps_base.html"
    
    
    class MarkerViewSet(viewsets.ReadOnlyModelViewSet):
        queryset = Point.objects.all()
        serializer_class = MarketSerializer
        bbox_filter_field = 'latitude'
        filter_backends = (filters.InBBoxFilter,)
    

-The javascript is configured like this:

```
const copy =
    "© <a href='https://www.openstreetmap.org/copyright'>OpenStreetMap</a> contributors";
const url = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png";
const osm = L.tileLayer(url, { attribution: copy });
const map = L.map("map", { layers: [osm], minZoom: 1 });
map.locate()
    .on("locationfound", (e) => map.setView(e.latlng, 8))
    .on("locationerror", () => map.setView([4.6406458,-74.0613249], 6));


async function load_markers() {
    const markers_url = `/api/point/?in_bbox=${map
        .getBounds()
        .toBBoxString()}`;
    const response = await fetch(markers_url);
    const geojson = await response.json();
    return geojson;
}

async function render_markers() {
    const markers = await load_markers();
    L.geoJSON(markers)
        .bindPopup((layer) => layer.feature.properties.name)
        .addTo(map);
}

map.on("moveend", render_markers);
```

error:

```
[23/Dec/2022 21:27:30] "GET /maps/base/ HTTP/1.1" 200 8682
  File "/home/cchavita/Documentos/venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1297, in build_lookup
    lhs = self.try_transform(lhs, lookup_name)
  File "/home/cchavita/Documentos/venv/lib/python3.10/site-packages/django/db/models/sql/query.py", line 1341, in try_transform
    raise FieldError(
django.core.exceptions.FieldError: Unsupported lookup 'contained' for FloatField or join on the field not permitted, perhaps you meant contains or icontains?
[23/Dec/2022 21:27:30] "GET /api/pdv/?in_bbox=-92.24121093750001,-4.434044005032582,-55.89843750000001,13.581920900545857 HTTP/1.1" 500 158085


```

The data that is stored in sqlite is known to have separate latitude and longitude, the help I need is to help me by validating why the serializer is not working and convert the query into geojson so that the javascript recognizes it so that it draws the points in your user-specified location, thank you in advance, thank you very much.

Make serializer to convert query to geojson, to be recognized by javascript using rest_framework_gis serializers

1

There are 1 answers

0
Carlos Chavita On BEST ANSWER

Friend, I think you should use this for serialization, good luck

localits = list_pdv_client
local_json = [l.serializer() for l in localits]
local_dict = {
     "type": "FeatureCollection",
     "features": local_json
}
data["markers"] = json.loads(json.dumps(local_dict))