Home > Software design >  How to use update in django admin with custom function
How to use update in django admin with custom function

Time:08-20

I am trying to make an admin action to update the price of an asset. It firsts set the last_update_date to today/now and I want to set the last_price to the current market price. The last part is not working as it is not updating.

admin.py:

@admin.action(description='Update asset price')
def update_price(modeladmin, request, queryset):
    queryset.update(last_update_date = timezone.now())
    for q in queryset:
        q.last_price = get_close_price(q.ticker) #does not change anything


class AssetAdmin(admin.ModelAdmin):
    actions = [update_price]

admin.site.register(Asset, AssetAdmin)

models.py:

class Asset(models.Model):

    ticker = models.CharField(
        verbose_name="Ticker",
        max_length=5,
        unique=True,
    )

    last_price = models.DecimalField(
        verbose_name="Last Price",
        max_digits=8,
        decimal_places=2,
        validators=[MinValueValidator(0)]
    )

    last_update_date = models.DateTimeField(
        verbose_name="Last update date"
    )

    class Meta:
        ordering = ['ticker']
    
    def __str__(self) -> str:
        return self.ticker

Custom function (from Alpha Advantage API)

def get_close_price(SYMBOL):
    params["symbol"] = SYMBOL
    close_price = get(URL, params).json()
    close_price = close_price["Global Quote"]["05. price"]
    return close_price #returns an int

CodePudding user response:

Since you're updating the last_update_date field using the update() on the queryset at the line:

queryset.update(last_update_date = timezone.now())

That's updating the value for each field in that given queryset. But as for the last_price field, this is not updating because you're not calling the save() as pointed out by @KlauseD. What you need to add is:

for q in queryset:
    q.last_price = get_close_price(q.ticker)
    q.save() # to save the updated price

Ideally, that should work.

  • Related