For other users who may find this, here's my workaround that allows me to find the geometry that matches an input geometry, both in vertex values and in vertex ordering. A Django wizard may be able to improve this and I would welcome any criticism.
class SegmentModel(models.Model):
...
@classmethod
def get_or_create_for_line(cls, line):
from django.contrib.gis.db.backends.postgis.adapter import PostGISAdapter
# We have to run a query outside of Manager.raw() because Manager.raw()
# always supplies a params argument to cursor.execute(), and sometimes
# the binary form of the line contains a percent sign.
from django.db import connection
with connection.cursor() as cursor:
sql = 'SELECT id FROM ride_segment WHERE line ~= {line_serialized} AND ST_OrderingEquals(line, {line_serialized})'.format(
line_serialized=str(PostGISAdapter(line)))
cursor.execute(sql)
ids = cursor.fetchmany()
if len(ids) > 1:
raise cls.MultipleObjectsReturned('Multiple segments for line {}'.format(line.ewkt))
elif len(ids) == 0:
return (cls.objects.create(line=line), True)
else:
return (cls.objects.get(id=ids[0][0]), False)