【问题标题】:Django - how to add data using conditional statement in a separate python scriptDjango - 如何在单独的 python 脚本中使用条件语句添加数据
【发布时间】: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 的语法应该是什么?

【问题讨论】:

    标签: python django


    【解决方案1】:
    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)
    

    【讨论】:

    • 应该用= 代替in 和= 而不是+=。
    • 感谢@AshishNitinPatil 我接受了这种情况,就像它是python代码一样。 :P
    • 太棒了!感谢 Ravi 和 Ashish 的帮助,解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-02
    • 2018-10-01
    • 1970-01-01
    • 2022-06-30
    相关资源
    最近更新 更多