I need some help for the creation of 2 queryset .
- Calculates the total of amounts of the objects considering the user as a common attribute.
- Given a specific user, calculate considering the categories, ordering the result in "in" and "out".
This is the information that already exists in my db (we can suppose that that's the serialized information of all the objects of my only Model:
[
{
"money": "-51.13",
"type": "out",
"category": "savings",
"user": "jane-doe"
},
{
"money": "2500",
"type": "in",
"category": "salary",
"user": "foo-bar"
},
{
"money": "-150.72",
"type": "out",
"category": "cellphone",
"user": "foo-bar"
},
{
"money": "-560.00",
"type": "out",
"category": "rent",
"user": "jane-doe"
},
This should be the output, queryset 1:
This consider all the data in the database.
[
{
"user": "jane-doe",
"total_in": "0",
"total_out": "-611.13"
},
{
"user": "foo-bar",
"total_in": "2500",
"total_out": "-150.72"
}
]
This should be the output, queryset 2:
This must consider de information of a specific user. The next information is just an example of the expected output. Suppose that the endpoint might be /operations/{user_email}/summary
{
"in": {
"salary": "1600.51",
"savings": "550.50"
},
"out": {
"groceries": "-41.23",
"rent": "-1286.68",
"transfer": "-605.15"
}
}
This is my models.py
from django.db import models
from rest_framework.exceptions import ValidationError
class Operation(models.Model):
TYPE_CHOICES = (
("out", "Out"),
("in", "In"),
)
type = models.CharField(
max_length=10, choices=TYPE_CHOICES, default="outflow"
)
money= models.DecimalField(max_digits=12, decimal_places=2,
validators=[])
category = models.CharField(max_length=15)
user = models.EmailField(max_length=254)
class Meta:
ordering = ("-user",)
def __str__(self):
return str(self.user)
def clean(self):
if self.type == 'out' and self.money > 0:
raise ValidationError('Out entries doesn\'t must be positive.')
if self.type == 'in' and self.money < 0:
raise ValidationError('In entries doesn\'t must be negative.')
This is my serializers.py in case you need.
from rest_framework import serializers
from core.base.models import Operation
class OperationsSerializer(serializers.ModelSerializer):
class Meta:
model = Operations
fields = ['money', 'type', 'category', 'user']