Reputation: 53
:)
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.
Upvotes: 2
Views: 196
Reputation: 476527
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]
)
Upvotes: 1