简体   繁体   中英

How do I do this Database Model in Django?

Django currently does not support the "Point" datatype in MySQL. That's why I created my own.

class PointField(models.Field):
    def db_type(self):
        return 'Point'

class Tag(models.Model):
    user = models.ForeignKey(User)
    utm = PointField()

As you can see, this works, and syncdb creates the model fine.

However, my current code calculates a length between two Points using raw SQL.

cursor.execute("SELECT user_id FROM life_tag WHERE\
              (GLength(LineStringFromWKB(LineString(asbinary(utm), asbinary(PointFromWKB(point(%s, %s)))))) < 55)...

This says: Select where the length between the given point and the table point is less than 55.

How can I do this with Django instead of RAW SQL? I don't want to do cursors and SELECT statements anymore. How can I modify the models.py in order to do this?

Your question is a bit unclear - are you just asking how to calculate the distance between 2 points? Or are you hoping the ORM will give you some functionality to do it?

If the latter, then that's not going to happen without some external assistance; geometry and geography are beyond the remit of most typical database mapping systems. You can always use the automatic mappings to retrieve the properties you're interested in and compare them manually using Pythagoras or whatever; no SQL there.

Regarding the 'external assistance' I mentioned, you could look at GeoDjango which might be of some use to you. (There is also GeoAlchemy for people with similar problems but not using Django for the ORM.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM