简体   繁体   中英

Django Saving Calculated Value to Model

:)

I'm a Django beginner and I'd like to ask for some help from you beautiful people.

Here's what I'm trying to accomplish:

I have a model - shown below -that I would like to contain a score for each symbol.

class Stock_Score(models.Model):

    Symbol = models.CharField(max_length=20, null=True)
    Score = models.FloatField(null=True)

To calculate that score, I'd like to use a second model which contains a list of stocks and a value called Yrs for each symbol:

class Stock_Data(models.Model):

    Symbol = models.CharField(max_length=20, null=True)
    Yrs = models.FloatField(null=True)

So what I was thinking was to import the Stock_Data model in my views.py, loop through the Symbols, check a simple if/else and then save the result to my first model under the "Score" field.

Something like this:

data = Stock_Data.objects.all()

for i in data:
      if i.Yrs > 10:
        Score = 1
      else:
        Score = 0

    Score.save()

Apologies for this garbage code, but I'd love some ideas about how I would be able to accomplish this:)

Thanks in advance.

You can calculate the number of Stock_Data objects for which Yrs is greater than 10 with:

from django.db.models import Count, Q

qs = Stock_Data.object.values('Symbol').annotate(
    nYgt10=Count('Yrs', filter=Q(Yrs__gt=10))
).order_by('Symbol')

next we can make Stock_Score objects and save these to the database:

Stock_Score.objects.bulk_create(
    [Stock_Score(Symbol=row['Symbol'], Score=row['nYgt10']) for row in qs]
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM