目的/意图

我创建了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添加到last_stock_price的语法应该是什么?

最佳答案

for stock in Stock.objects.all():
    if stock.ticker_code == 'GOOJ':
        stock.latest_stock_price = 1.234
        stock.save()


要么

Stock.objects.filter(ticker_code='GOOJ').update(latest_stock_price=1.234)

关于python - Django-如何在单独的python脚本中使用条件语句添加数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43169112/

10-12 05:00
查看更多