Is there a way to save a tuple to a django model?
example:
Class User(models.Model):
location = models.tupleField()
where User.location = (longitude, latitude)
Maybe you are looking for GeoDjango's PointField:
from django.contrib.gis.db import models
Class User(models.Model):
location = models.PointField(help_text="Represented as (longitude, latitude)”)
Honestly, i didn't see tupleField in django documentation. I think better approach is add two fields
longitude and latitude or create another model to store location and in User model add ForeignKey.
If you feel the need to save tuples in a single field, you should really look into relationships. That's the reason they were created.
Old answer:
This answer is assuming you're really saving locations.
If you're using PostgreSQL, you can use PostGIS. MySQL and Oracle has spacial fields built-in.
Django already supports Geo data. E.g. -
from django.contrib.gis.db import models
class ModelName(models.Model):
centroid = models.GeometryField(blank=True, null=True)
Then you can make all sorts of geo queries(e.g. find places that are within a specified area, sorted by distance etc) and your DBMS will take care of them. Plus from that single field, you can access your data like -
lat, long = [modelobject.centroid.x, modelobject.centroid.y]
# Or you can just use .x or .y directly
You can read more about them in the Geodjango documentation.
I recommend the Django-Geoposition app, and for extra, you can see the Latitude and Longitude in Google Maps.
I think this answer could help here as well.
--
As #p14z suggests, the best way to save my tuple was the ArrayField. For my example, I just wanted to save a Polygon extent, with this format:
(3.7739613717694787, 50.31527681737183, 4.726162032377, 50.49743217278623)
from django.contrib.postgres.fields import ArrayField
my_tuple_field = ArrayField(models.FloatField(), size=4, null=True)
Related
I'm using django-filters lib https://django-filter.readthedocs.io/en/master/index.html. I need to make chained select dropdown in my filters.
I knew how to make it with simple django-forms like here https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html.
When user pick region, i need to show cities in this region? Have someone idea or solution how to build filters like this?
Integrate django-smart-selects with how you perform the filtering.
This package allows you to quickly filter or group “chained” models by adding a custom foreign key or many to many field to your models. This will use an AJAX query to load only the applicable chained objects.
In analogy to the original question for Region -> City, the documentation's example is Continent -> Country which fits exactly to what is needed.
Once you select a continent, if you want only the countries on that continent to be available, you can use a ChainedForeignKey on the Location model:
class Location(models.Model):
continent = models.ForeignKey(Continent)
country = ChainedForeignKey(
Country,
chained_field="continent", # Location.continent
chained_model_field="continent", # Country.continent
show_all=False, # only the filtered results should be shown
auto_choose=True,
sort=True)
Related question:
How to use django-smart-select
I have a pandas DataFrame from which I want to create a model whose fields are the df columns (and sets the right "Field" type for django).
Googled around but could only find bulk_create() tips, which, for my understanding, creates different Models.
My knowledge level: Django tutorial done, trying to exercise by creating this model from a big dataframe (many columns).
EDIT:
In practice, what I think I need is a way to write this part (in a model.py class):
first_name = models.CharField(max_length=200)
surname = models.CharField(max_length=200)
run_date = models.DateTimeField('run_date')
...
in an automatic way by looking at a dataframe with 30+ columns and defining a field for each of them.
I suspect I'm probably thinking it in a wrong way, so I would like some redirection of that kind, if needed.
I want to store my users location using longitude and latitude, at the moment this comes from Google Maps, but I will be using GeoDango and some point to work out distances between to points also.
However, my first confusion is which field in Django I should be using to store the longitude and latitude values? The information I'm getting is conflicting.
The official documentation uses a FloatField
https://docs.djangoproject.com/en/dev/ref/contrib/gis/tutorial/#geographic-models
lon = models.FloatField()
lat = models.FloatField()
Where almost every answer on stackoverflow shows a DecimalField
long = models.DecimalField(max_digits=8, decimal_places=3)
lat = models.DecimalField(max_digits=8, decimal_places=3)
So what should I be using?
Float is generally an approximation, see here for some simple examples. You could get very nice results modifying your model to something like DecimalField(max_digits=9, decimal_places=6), since decimals are very important in coordinates but using more than 6 is basically meaningless.
Use PointField to store lat long
p = Point(85.3240, 27.7172,srid=4326)
Django: 1.X:
https://docs.djangoproject.com/en/1.11/ref/contrib/gis/model-api/#pointfield
Django: 2.X:
https://docs.djangoproject.com/en/2.2/ref/contrib/gis/model-api/#pointfield
Django: 3.X:
https://docs.djangoproject.com/en/3.0/ref/contrib/gis/model-api/#pointfield
The suggestion here to use DecimalField(max_digits=9, decimal_places=6) resulted in errors for me when trying to save locations from Google Maps.
If we assume that the most common use case is retrieving point locations from the Maps API, and a typical URL from Google Maps when right-clicking and selecting "What's Here?" yields something like:
https://www.google.com/maps/place/37°48'52.3"N+122°17'09.1"W/#37.814532,-122.2880467,17z
(random place)
So the longitude has 15 places before and after the decimal, which is why the accepted answer doesn't work. Since there's no reason to validate for "as short as possible" and db storage is cheap, I'm using:
max_digits=22,
decimal_places=16)
I'm building a django app that requires to display (on google map) items near the user current location. (ie. the nearest coffee shop kind of request).
I haven't decided how I will capture those items' location in db.
The requirements aren't final but I'm guessing the user will want to sort by distance, etc.
My question is what solution should I look into?
I looked at geodjango but it seems to be an overkill.
Could you please tell me what solution you would use and why?
Thanks everyone!
You will need to use RDBMS like MySQL or postgresql. Then, create your objects (e.g: cafeshops) with latitude and longitude as flout. Get the user's latitude and longitude and look it up via sin and cos functions.
You will need to write a raw sql query to look up objects based on their latitude and longitude.
Read this: http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL
Take a look at this: Filter zipcodes by proximity in Django with the Spherical Law of Cosines
and this: latitude/longitude find nearest latitude/longitude - complex sql or complex calculation
I have the following model for a song:
class Song(models.Model):
name = models.CharField(max_length=255)
artist = models.CharField(max_length=255)
rating = models.SmallIntegerField()
I want to know if there is a better way to store the rating for a Song, as it is a scale from 1 to 5?
Better in the sense that it will take less space to store the same data in the database.
I have read through the Django documentation and the SmallIntegerField looks like the smallest value field.
But it can hold values ranging from "-32768 to 32767" which is overkill for my needs, as I just want to store 5 unique values (1 through 5).
Is there a smaller field type? Should I use a CharField(max_length=1)?
Any suggestions?
You can go one smaller and use a PositiveSmallIntegerField, which is guaranteed in all databases to store all integers from 0 to 32,767 (i.e. the positive range of a signed short).
The ideal answer for storage optimization would be to use something like a bit field where you can store scores in binary, but there is no field type like that in built-in Django that represents numerical values. You'd have to make your own Field that stores a 3-bit unsigned integer, with entails all of the appropriate development required to glue it into Django's ORM.