Django objects.update_or_create

7 python api django 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)
Run Code Online (Sandbox Code Playgroud)

模型.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)
Run Code Online (Sandbox Code Playgroud)

视图.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})
Run Code Online (Sandbox Code Playgroud)

模板.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 %}
Run Code Online (Sandbox Code Playgroud)

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

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

加密价格 - 第 1 页,共 21 页。最后 » 排名符号名称价格市值 (美元) 24 小时。交易量(美元) 1 BTC 比特币 3795.6465 $ 66594617840.0 $ 8296474984.64 $ 2 ETH 以太坊 143.9996 $ 15106822040.0 $ 5043716023.22 $

在第二页上:

« 第一 | 以前的加密价格 - 第 2 页,共 22 页。最后 » 排名符号名称价格市值 (美元) 24 小时。交易量(美元) 101 BTC 比特币 3798.3016 $ 66641201438.0 $ 8304474934.43 $ 102 ETH 以太坊 144.0825 $ 15115524904.0 $ 5048205218.0 $

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

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

亲切的问候

dir*_*ten 14

你误解了update_or_create工作原理。这是文档所说的:

update_or_create方法尝试根据给定的kwargs. 如果找到匹配项,它会更新defaults字典中传递的字段。

因此,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))
)
Run Code Online (Sandbox Code Playgroud)


Dan*_*man 10

您正在将查询中的所有字段用于现有实例。您只需要在那里使用唯一的,而在defaults字典中使用其余的。

CryptoPrices.objects.update_or_create(
   key=exchange_rate['id'],
   symbol=exchange_rate['symbol'],
   defaults={             
       "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)
    })
Run Code Online (Sandbox Code Playgroud)