I am a django beginner and trying to programm a simple geo application. My setup: django/geodjango + leaflet. Everything works fine and geo objects (GeoObject) are displayed. But now I want to add aditional properties ("status") from another model and display them also via leaflet - but I´m stuck.
my models.py:
class GeoObject(models.Model):
name = models.CharField(verbose_name="name", max_length=20)
location = models.PointField(srid=4326)
class Status(models.Model):
geoobject = models.OneToOneField(GeoObject, on_delete=models.CASCADE, primary_key=True, default=0, unique=True)
status = models.CharField(verbose_name="Sensor", max_length=20)
my views.py:
def GeoMapView(request): #view to display leaflet map with geo objects
q=Sensor.objects.all()
context = {'q':q}
return render(request, 'xitylytix_sensors/sensor_map.html', context)
def GeoData(request): #sending geo data
q=GeoObject.objects.all()
geo_data = serialize('geojson', q)
return HttpResponse(geo_data, content_type='json')
my urls.py
urlpatterns = [
path('geomap/', views.GeoMapView, name='geo_map'), #display via template/leaflet map
path('geodata/', views.GeoData, name='geo_data'), #sending geo data
]
json data:
{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:4326"}}, "features": [{"type": "Feature", "properties": {"name": "001", "pk": "1"}, "geometry": {"type": "Point", "coordinates": [8.849315642079313, 50.07892796957105]}}, ...
I tried with one to one relation (see model), but "status" in the json file is missing in "properties". Does anyone have an idea?
What I am also tried:
What I want is this, but its not working, just retriving objects without GeoObject data:
q = Status.objects.all().only('status','geoobject__name', 'geoobject__location',)
Query is working, but I am retrieving only list of dicts, what I can not use to serialize:
q = Status.objects.all().values('status','geoobject__name', 'geoobject__location',)
I finaly found a solution which is working for me:
views.py:
def createleafletobject(q):
queryset = []
for element in table:
LeafObj = LeafletObject(
name = element['name'],
location = element['location'],
geoobject = element['geoobject'],
status = element['status],
)
queryset.append(LeafObj)
return queryset
def GeoMapView(request): #view to display leaflet map with geo objects
q=Sensor.objects.all()
context = {'q':q}
return render(request, 'xitylytix_sensors/sensor_map.html', context)
def GeoData(request): #sending geo data
q = Status.objects.all().values('geoobject__name', 'geoobject__location', 'geoobject', 'status')
q = createleafletobject(q)
geo_data = serialize('geojson', q)
return HttpResponse(geo_data, content_type='json')
So what I am doing is to query data form two object via "values()", receiving and dictionary and transforming with my self written "createleafletobject(table)" class into an object, which I am szerializing and passing to leaflet.