Django model with crud operations
Working with Django and stuck on how to make my model c.r.u.d operations using Models.Manager. The fields I'm working with are zipcode, city, latitude, longitude, coordinates and current time. I would like to insert a new entry with zipcode, city, latitude, longitude and current time. Also, would like to update an existing record by zipcode. Lastly, get a record by zipcode returning city and get a record by zipcode returning city, state, and coordinates( latitude and longitude ).
from django.db开发者_StackOverflow中文版 import models
from datetime import datetime
class Name(models.Model):
zipcode = models.CharField(max_length=5, primary=True, blank=False)
city = models.CharField(max_length=50, blank=False)
state = models.CharField(max_length=2, blank=False)
latitue = models.CharField(max_length=15, blank=False)
longitue = models.CharField(max_length=15, blank=False)
curr_time = models.datetime(default=datetime.now, blank=False)
You should read the django documentation some more https://docs.djangoproject.com/en/1.3/. The tutorial has a portion talking about saving and updating models. However, in answer to your question...
from models import Name
from datetime import datetime
# create a new model
name = Name(city='New York', state='NY')
# fields can also be set this way
name.zipcode = '10027'
# save the model to the database
name.save()
# find a model by zipcode
name = Name.objects.filter(zipcode='10027')
# modify it
name.curr_time = datetime.now()
# save it
name.save()
Easy, right?
For your curr_time field, you may use:
curr_time = models.DateField(auto_now=True)
# or auto_now_add=True, if you want set this field only at the creation.
More here: https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield
精彩评论