Django模型与CRUD操作

0 投票
2 回答
2102 浏览
提问于 2025-04-16 19:57

我在使用Django的时候,遇到了一些问题,想知道怎么用Models.Manager来进行模型的增删改查操作。我的模型里有一些字段,包括邮政编码、城市、纬度、经度、坐标和当前时间。我想要插入一个新的记录,包含邮政编码、城市、纬度、经度和当前时间。同时,我还想通过邮政编码来更新一个已有的记录。最后,我希望能通过邮政编码获取一个记录,返回城市信息,以及通过邮政编码获取一个记录,返回城市、州和坐标(纬度和经度)。

from django.db 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)

2 个回答

0

对于你的 curr_time 字段,你可以使用:

curr_time = models.DateField(auto_now=True)
# or auto_now_add=True, if you want set this field only at the creation.

更多信息请查看:https://docs.djangoproject.com/en/dev/ref/models/fields/#datefield

3

你应该多看看Django的文档,里面有很多有用的信息,特别是关于保存和更新模型的部分。你可以在这里找到它:https://docs.djangoproject.com/en/1.3/。不过,针对你的问题...

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()

这很简单,对吧?

撰写回答