'Geodjango model combined with non geo model
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',)
Solution 1:[1]
Why are you trying to do that? You can simply create object in views and add data to your GeoObject model.just add data column to your database and after that in views you can add specific data to your model.
def GeoData(request):
q=GeoObject.objects.all()
for item in queryset:
GeoObject.objects.create(
something = item.queryset(data)
)
geo_data = serialize('geojson', q)
return HttpResponse(geo_data, content_type='json')
And if you want to access data in another model, you should use foreign key.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | marc_s |
