python - Django objects.update_or_create

标签 python django api templates

我有一个在 celery 中运行的 period_task 查询最新的加密货币价格,但出于某种原因,每次想要显示数据时,我都没有得到更新的记录,我只是得到了新的记录,而由于某种原因,旧的记录被保留了下来。

任务.py

@periodic_task(run_every=(crontab(minute='*/1')), name="Update Crypto rate(s)", ignore_result=True)
def get_exchange_rate():
    api_url = "https://api.coinmarketcap.com/v1/ticker/"
    try:
        exchange_rates = requests.get(api_url).json()
        for exchange_rate in exchange_rates:
            CryptoPrices.objects.update_or_create(key=exchange_rate['id'],
                                                  symbol=exchange_rate['symbol'],
                                                  market_cap_usd=round(float(exchange_rate['market_cap_usd']), 3),
                                                  volume_usd_24h=round(float(exchange_rate['24h_volume_usd']), 3),
                                                  defaults={'value': round(float(exchange_rate['price_usd']), 3)}
                                                  )
        logger.info("Crypto exchange rate(s) updated successfully.")
    except Exception as e:
        print(e)

模型.py
class CryptoPrices(models.Model):
    key = models.CharField(max_length=255)
    value = models.CharField(max_length=255)
    symbol = models.CharField(max_length=255)
    volume_usd_24h = models.CharField(max_length=255)
    market_cap_usd = models.CharField(max_length=255)

View .py
def crypto_ticker(request):
        list_prices = CryptoPrices.objects.get_queryset().order_by('pk')
        paginator = Paginator(list_prices, 100)  # Show 100 prices per page
        page = request.GET.get('page')
        price = paginator.get_page(page)
        return render(request, 'crypto_ticker.html', {'price': price})

模板.html:
{% extends 'base.html' %}
{% load readmore %}

{% block breadcrumbs %}
    {{ block.super }} » <a href="{% url 'post_list' %}">Posts </a> »
    <a href="{% url 'crypto_ticker' %}">Crypto ticker</a>
{% endblock %}


{% block content %}

    <!DOCTYPE html>
    <html>
    <head>
        <title>Crypto ticker</title>
    </head>

    <body>
    <h1 class="center">Crypto ticker</h1>
    <hr class="hr-style">
    <div class="center">
        <h4>{{ prices }} Here you can find all frequently asked questions <br>
            if you still have still have any open points, please contact the <a href="#">support</a>.</h4>
    </div>
    <br>
    <div class="paginator">
        <span>
         {% if price.has_previous %}
            <a href="?page=1">&laquo; First <a> |</a></a>
            <a href="?page={{ price.previous_page_number }}">Previous</a>
        {% endif %}

        {% if price.has_next %}
            <span> Crypto prices - Page {{ price.number }} of {{ price.paginator.num_pages }}.</span>
            <a href="?page={{ price.next_page_number }}">Next<a> |</a></a>
            <a href="?page={{ price.paginator.num_pages }}">Last &raquo;</a>
        {% endif %}
       </span>
   </div>
    <table class="table centercontentfloat class-three-box">
        <thead>
            <tr style="font-size: small">
                <th>Ranking</th>
                <th>Symbol</th>
                <th>Name</th>
                <th>Price</th>
                <th>Market Cap (USD)</th>
                <th>24 hrs. Volume (USD)</th>
            </tr>
        </thead>
        <tbody>
        {% for price in price %}
            <tr style="font-size: small">
                <td>{{ price.id }}</td>
                <td>{{ price.symbol }}</td>
                <td>{{ price.key }}</td>
                <td>{{ price.value }} $</td>
                <td style="font-size: small">{{ price.market_cap_usd }} $</td>
                <td style="font-size: small">{{ price.volume_usd_24h }} $</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    <div class="paginator">
        <span>
            {% if price.has_previous %}
            <a href="?page=1">&laquo; First <a> |</a></a>
            <a href="?page={{ price.previous_page_number }}">Previous</a>
        {% endif %}

        {% if price.has_next %}
            <span> Crypto prices - Page {{ price.number }} of {{ price.paginator.num_pages }}.</span>
            <a href="?page={{ price.next_page_number }}">Next<a> |</a></a>
            <a href="?page={{ price.paginator.num_pages }}">Last &raquo;</a>
        {% endif %}
       </span>
    </div>
{% endblock %}

为什么我从 coinmarketcap api 获取的记录被保存/显示两次,有什么明显的原因吗?

如果我浏览页面,我会返回如下内容:

Crypto prices - Page 1 of 21. Next | Last » Ranking Symbol Name Price Market Cap (USD) 24 hrs. Volume (USD) 1 BTC bitcoin 3795.6465 $ 66594617840.0 $ 8296474984.64 $ 2 ETH ethereum 143.9996 $ 15106822040.0 $ 5043716023.22 $



在第二页上:

« First | Previous Crypto prices - Page 2 of 22. Next | Last » Ranking Symbol Name Price Market Cap (USD) 24 hrs. Volume (USD) 101 BTC bitcoin 3798.3016 $ 66641201438.0 $ 8304474934.43 $ 102 ETH ethereum 144.0825 $ 15115524904.0 $ 5048205218.98 $



我不希望 BTC 也在第二页,只有一次在第一页?!?

看起来如果我浏览页面,记录不会得到更新,它们会在每次 period_task 运行后一个接一个地保存

亲切的问候

最佳答案

你误解了 update_or_create作品。这是什么docs说:

The update_or_create method tries to fetch an object from database based on the given kwargs. If a match is found, it updates the fields passed in the defaults dictionary.



所以在 kwargs您只传递获得匹配所需的值,而不是更新。大概路过idsymbol应该是唯一的 kwargs你需要。你要更新的所有参数都需要传递给defaults .
CryptoPrices.objects.update_or_create(
    key=exchange_rate['id'],
    symbol=exchange_rate['symbol'],
    defaults=dict(
        market_cap_usd=round(float(exchange_rate['market_cap_usd']), 3),
        volume_usd_24h=round(float(exchange_rate['24h_volume_usd']), 3),
        value= round(float(exchange_rate['price_usd']), 3))
)

关于python - Django objects.update_or_create,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54749170/

相关文章:

python - Django 将错误列表输出为字符串而不是 html

django - 为 django 应用程序提供服务时出现 uwsgi 段错误

python - 在 Django 中定义 View 和 url。为什么不使用括号来调用函数?

node.js - 我应该如何存储由 RESTful API 生成的 token ?

java - JaxRS 读取文本/xml 响应 MessageBodyProviderNotFoundException

python - 避免 python 设置时间

python - 从 postgreSQL 数据库(Django 站点)备份所有数据

python - 如何用其他数据框中的值替换 pandas 中的整个单元格?

python - pipenv 安装给出无法加载路径错误

php - 如何使用 api 在 Google map 中仅显示一个国家或特定区域?