Newb here. Apologies in advance.
I have:
class Place(models.Model):
address = models.CharField(max_length=100)
[...]
def coordinates(self):
location = Location(self.address)
return location
"Location" method works and is not the problem. I can see Place.coordinates in template just fine but I want to be able to store them in the db and thus, access them in views.py.
My question is, how can I store coordinates in m开发者_StackOverflow中文版y db so that the calculation is done only once (when the form is initially filled out)?
Thank you! (and I've read all the docs, chances are I've read over the solution and just don't understand it, so if this is obvious, you'll have to excuse me)
First, define a model for the coordinates:
class Coordinates(models.Model):
[whatever coordinates consist of]
Then add coordinates
as a field to the Place
model.
class Place(models.Model):
address = models.CharField(max_length=100)
[...]
coordinates = models.ForeignKey(Coordinates)
That way you've specified that the coordinates are stored in the db.
Now, in the view in which you add a new Place to the database, first create the Coordinates and then add the Place to the database:
def add_place(form):
address = form.cleaned_data['address']
coordinates = Coordinates.objects.get_or_create(Location(address))
[...]
place =
Place.objects.get_or_create(address=address, coordinates=coordinates, ...)
精彩评论