【发布时间】:2017-04-02 13:50:27
【问题描述】:
目的/意图
我创建了 Django 模型,结果是一个 sqlite3 数据库。我现在想根据一些条件逻辑使用单独的 python 脚本添加到该数据库中。
问题
我是 Django 和 Python 的新手,所以我不知道如何查询数据库,然后使用单独的 python 脚本根据查询的返回结果添加一些值。
这是我的 Models.py:
from django.db import models
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
# Create your models here.
class Author(models.Model):
'''
Model representing the Author of the stocknote.
'''
user_id = models.ForeignKey('auth.User')
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Stock(models.Model):
'''
Model representing the stock info.
'''
author = models.ForeignKey(Author)
ticker_code = models.CharField(max_length=10, null=True, blank=True)
latest_stock_price = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True)
datetime_of_last_quote = models.DateTimeField(default=timezone.now)
def __str__(self):
return self.ticker_code
class Note(models.Model):
'''
Model representing the Authors note.
'''
author = models.ForeignKey(Author)
note = models.TextField()
ticker_code = models.ForeignKey(Stock)
date_note_created = models.DateTimeField(default=timezone.now)
alert_price = models.DecimalField(max_digits=20, decimal_places=4, null=True, blank=True)
def __str__(self):
return self.note
现在假设我已将数据添加到数据库中,因此它包含所有字段中的数据,但字段“latest_stock_price”为空。
我想在一个单独的 python 脚本中做的 - 让我们称之为 interrogate-db.py - 有这样的程序逻辑:
If 'GOOG' is in 'ticker_code' then
add '1.234' to the latest_stock_price for GOOJ
我在编写 interrogate-db.py 时能达到的最佳效果是:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject_project.settings')
import django
django.setup()
from myproject.models import Author, Stock, Note
def add_latest_price():
for t in Stock.objects.values_list('ticker_code'):
if 'GOOJ' in t:
...What goes here?...
如果 GOOJ 在 t 中,将 1.234 添加到 latest_stock_price 的语法应该是什么?
【问题讨论】: