GeoDjango equivalent of ST_GeomFromGeoJson? - django

What is the equivalent of ST_GeomFromGeojson() in GeoDjango?
I'm looking for it in GeoDjango's documentation but there's only AsGeoJSON as its output format. This can be done both using annotate and serialize.
But what if I want to have a GeoJson object that I need to turn back to Geom?
Use Case:
geom_test = Geom.objects.filter(poly__within = [ST_GeomFromGeoJSON(d)])

From the docs
GEOSGeometry objects may be created in a few ways. The first is to simply instantiate the object on some spatial input – the following are examples of creating the same geometry from WKT, HEX, WKB, and GeoJSON:
# Other stuff I cut out.
pnt = GEOSGeometry('{ "type": "Point", "coordinates": [ 5.000000, 23.000000 ] }') # GeoJSON
So essentially GEOSGeometry(GeoJSONString)

Related

Geodjango OSMWidget is not returning actual coordinates

I am using the OSMWIdget in my PointField form. I am able to get the values returned by the widget
{ "type": "Point", "coordinates": [ 13468873.706852857023478, 1639089.007222681771964 ] }
But the thing is, these are not 'standard' coordinates. I had already set my defaults to 'default_lon' : 120.993173,'default_lat' : 14.564752 so I expected to get these as results.
Also I am not saving any 'spatial' objects to spatialite because I only need the lon and lat as primitive dataypes and I would rather stick to having a single database in our project and that db is not a spatial db.

NgramField returning resutls based on substring of the query term

I have a Warehouse Model which is getting index as follows
class WarehouseIndex(SearchIndex, Indexable):
"""
SearchIndex Class that stored indexes for Model Warehouse
"""
text = CharField(document=True, use_template=True)
search_auto = NgramField()
....
def get_model(self):
return WareHouse
In my shell I am running the following sqs query.
>>> sqs = SearchQuerySet().models(WareHouse)
>>> sqs.filter(customers=3).filter(search_auto='pondicherry')
This returns result consisting of results that do not have exact term pondicherry it also provides me some results that match terms like ich, che, ndi, etc.
I have even tried using __exact and Exact but all return the same result?
EDIT: Index mapping, Index Setting
How can I avoid this and provide result only of term pondicherry?
It seems to be related to this open issue
This is because your search_auto ngram field has the same index and search analyzer and hence your search term pondicherry also gets ngramed at search time. The only way to fix this is to set a different search_analyzer for your search_auto field, standard would be a good fit.
You can change your search_auto field mapping with this:
curl -XPUT localhost:9200/haystack/_mapping/modelresult -d '{
"properties": {
"search_auto": {
"type": "string",
"analyzer": "ngram_analyzer",
"search_analyzer": "standard"
}
}
}'
As #Val has stated in the above answer, the error was because search_analyzer and indexed_analyzer are same which caused the issue,
As we all know haystack is very inflexible in setting up the basic elasticsearch configuration, I installed elasticstack and in my setting.py changed the backend to it's elasticsearch_backend as suggest and additionally added the following 2 configurations
# elasticslack setting
ELASTICSEARCH_DEFAULT_ANALYZER = 'snowball'
ELASTICSEARCH_DEFAULT_NGRAM_SEARCH_ANALYZER = 'standard'
this seemed to solve my problem.

Using knockout destroy() with django deserializer

In knockout.js there is a function called destroy() See bottom of this page
It says that it is useful for Rails developers as it adds a _destroy attribute to a object in an observerable array
Im using django and trying to use the same function to know which objects to delete from my database - and as far as i understand a django deserialized object only contains the and pk what is in the fields object
this is what the json looks like:
{"pk": 1,
"model": "eventmanager.datetimelocgroup",
"fields": {"event": 10},
"_destroy": "true"
}
As of now i have very ugly but working code - i was wondering if there is any shorter way to detect if a deserialized object had a destroy flag
my current code looks like this
ra = []
removejson = json.loads(eventslist)
for i,a in enumerate(removejson):
if '_destroy' in a:
ra.append(i)
for index,event in enumerate(serializers.deserialize("json", eventslist)):
if index in ra:
try:
e = Event.objects.get(id = event.object.pk)
e.delete()
except ObjectDoesNotExist:
pass
else:
event.save()
I was wondering if there is a better way than going through the json multiple time
This oneliner should work (please understand it before trying it out):
Event.objects.filter(
id__in = [
x['fields']['event'] for x in json.loads(eventslist) if '_destroy' in x
]
).delete()

Several Fields on a Single Row while using CBVs & Bootstrap

I am working on a project using Bootstrap and making use of Class Based Views. The forms that are rendered automagically are quite nice. But I want to make one simple change. Given a model that has city, state & zip fields, I want the form to render all three off those fields on the same row.
Name [ ]
Addr [ ]
City [ ] State [ ] Zip [ ] <-- 3 fields, 1 row
I assume this is a pretty common task that has an elegant solution, but I have not found it. I was hoping django-crispyforms Row('city', 'state', 'zip'), would do in the Layout but that did not work.
I haven't used crispy forms in a while but I believe with bootstrap you have to do something like example below because you cannot simply insert form elements into a row:
Row(
Div('city', css_class='span4'),
Div('state', css_class='span4'),
Div('zip', css_class='span4')
)

Django - Serializing model with additional data

I am trying to serialize some model data along with some extra information like so:
data = {
'model_data': serializers.serialize('json', SomeModel._default_manager.all(), fields=('name','last_updated')),
'urls': {
'updateURL':'http://www.bbc.co.uk',
},
}
json = simplejson.dumps(data)
It seams my 'model_data' object is being serialized twice as it seems to be returned as a string and not a valid json object:
Object
model_data: "[{"pk": 1, "model": "models.SomeModel", "fields": {"last_updated": null, "name": "Name test"}}]"
urls: Object
What am I doing wrong here?
How about having the value of the model_data field be handled again by another JSON processor? I think it will be the same, since the JSON processor always expects a string that is always in the correct format.