HiPhone_BE/graph/methods.py

56 lines
1.6 KiB
Python
Raw Permalink Normal View History

2023-06-23 02:09:00 +09:00
from django.db.models import Avg
from django.utils import timezone
from graph.models import Transaction, MonthlyTransaction
from market.models import Product
def create_transaction(post):
transaction = Transaction.objects.create(
product=post.product, price=post.price
)
return transaction
def get_average_price(transactions):
average = transactions.aggregate(Avg("price"))["price__avg"] or 0
return round(average, -2)
def create_monthly_transaction():
year = timezone.now().year
month = timezone.now().month
products = Product.objects.all()
for product in products:
if MonthlyTransaction.objects.filter(
product=product, year=year, month=month
).exists():
continue
transactions = Transaction.objects.filter(product=product)
if transactions:
price = get_average_price(transactions)
MonthlyTransaction.objects.create(
product=product,
year=year,
month=month,
price=price,
)
def create_monthly_transaction_by_product(product):
year = timezone.now().year
month = timezone.now().month
if MonthlyTransaction.objects.filter(
product=product, year=year, month=month
).exists():
return
transactions = Transaction.objects.filter(product=product)
if transactions:
price = get_average_price(transactions)
MonthlyTransaction.objects.create(
product=product,
year=year,
month=month,
price=price,
)