Auto guess Profit/Loss from django and react

Viewed 36

I'm creating and analysis website using Yahoo Finance API.

models.py

class Stock(models.Model):
    money_to_invest = models.CharField(max_length=100)
    stock_price = models.CharField(max_length=100)
    company = models.CharField(max_length=50)
    profit_or_loss = models.CharField(max_length=20)
    author = models.ForeignKey(User, on_delete=models.CASCADE) 

serializers.py

class StockSerializer(serializers.ModelSerializer):
    class Meta:
        model = Stock
        fields = '__all__'

views.py

class StockViewSet(viewsets.ModelViewSet):
    queryset = Stock.objects.all()
    serializer_class = StockSerializer
    permission_classes = [permissions.IsAuthenticated, ]
    authentication_classes = [JWTAuthentication, ]

    def get_queryset(self):
        user = self.request.user
        return Stock.objects.filter(author=user).all()

React Part

const onInputChange = (e) => setformData({ ...formData, [e.target.name]: e.target.value });
<div className="form-group">
<input
className="form-control"
type="text"
placeholder="Profit or Loss"
name="profit_or_loss"
value={money_to_invest > regular_market_price ? 'Profit' : 'Loss'}
onChange={(e) => onInputChange(e)}
readOnly
/>
</div>

In profit_or_loss field want to auto save value Profit or Loss. if money_to_invest is greater than stock_price than is is Profit. How it can be possible through Django and React. I'm also using Redux for state management.

1 Answers

There is no need to store this in a field: the field is functionally completely dependent on other fields, so this would introduce data duplication. You can annotate the Stock model with a Case expression [Django-doc] when you need this:

from django.db.models import Case, F, Value, When

Stock.objects.annotate(
    profit_or_loss=Case(
        When(money_to_invest__gt=F('stock_price'), then=Value('Profit')),
        default=Value('Loss')
    )
)
Related