django - 如何将datetime字段保存(更新)到数据库

时间:2018-05-20 15:32:08

标签: django python-3.x django-models django-views python-datetime

我遇到了Django DateTimeField的一些问题。我希望我的脚本在发生某些情况时在数据库中将 expiration_date 字段添加7天。

models.py

class TrainingPlan(models.Model):
    user = models.OneToOneField(User, on_delete='CASCADE')
    exercise_list = models.ManyToManyField(Exercise)
    expiration_date = models.DateTimeField(default=datetime.now(timezone.utc))
    reps = models.PositiveIntegerField(default=10)

views.py

 def check_plan_expiration_date():
    user_exp_date = user_trainingplan.expiration_date
    now = datetime.now(timezone.utc)
    if user_exp_date <= now:
        user_exp_date = datetime.now(timezone.utc)+timedelta(days=7)
        user_exp_date.save()
    else:
        return user_exp_date

我得到的错误: 'datetime.datetime'对象没有属性'save'

2 个答案:

答案 0 :(得分:0)

使用模型

def find_paths(node, cities, path, distance):
    # Add way point
    path.append(node)
    #print('path:', path)

# Fork paths for all possible cities not yet used
    for city in cities:
        if (city not in path) and (node in cities[city]):
            find_paths(city, dict(cities), list(path), distance)
#What has to be:
count = 0 # avoid adding end paths twice
    for city in cities[node].keys(): # only recurse on children not the whole list
        if city not in visited: 
            count += 1
            find_paths(city, cities, path, distance, visited)
    if count > 0 : # only add again if there were children
        path.append(node)
#////////////

if __name__ == '__main__':
    cities = {
    'Arad': {'Sibiu': 140, 'Timisoara': 118, 'Zerind': 75},
    'Hirsova': {'Eforie': 86, 'Urziceni': 98},
    'Bucharest': {'Fagaras': 211, 'Giurgiu': 90, 'Pitesti': 101, 'Urziceni': 85},
    'Craiova': {'Drobeta': 120, 'Pitesti': 138, 'Rimnicu Vileea': 146},
    'Drobeta': {'Craiova': 120, 'Mehadia': 75},
    'Eforie': {'Hirsova': 86},
    'Fagaras': {'Bucharest': 211, 'Sibiu': 99},
    'Giurgiu': {'Bucharest': 90},
    'Iasi': {'Neamt': 87, 'Vaslui': 92},
    'Lugoj': {'Mehadia': 70, 'Timisoara': 111},
    'Mehadia': {'Drobeta': 75, 'Lugoj': 70},
    'Neamt': {'Iasi': 87},
    'Oradea': {'Sibiu': 151, 'Zerind': 71},
    'Pitesti': {'Bucharest': 101, 'Craiova': 138, 'Rimnicu Vileea': 97},
    'Rimnicu Vileea': {'Craiova': 146, 'Pitesti': 97, 'Sibiu': 80},
    'Sibiu': {'Arad': 140, 'Fagaras': 99, 'Oradea': 151, 'Rimnicu Vileea': 80},
    'Timisoara': {'Arad': 118, 'Lugoj': 111},
    'Urziceni': {'Bucharest': 85, 'Hirsova': 98, 'Vaslui': 142},
    'Vaslui': {'Iasi': 92, 'Urziceni': 142},
    'Zerind': {'Arad': 75, 'Oradea': 71}
    }

    #print("Start: Neamt")
    find_paths('Neamt', cities, [], 0)

答案 1 :(得分:0)

您在错误的对象/变量上调用@Qualifier("dataSource") @Autowired DataSource dataSource; 方法。您想将新save()设置为user_exp_date属性并致电user_trainingplan.expiration_date

user_trainingplan.save()