Refactor database models to majorly increase queries needed and decrease load times of home from 30 secs to 5 sec (we will be caching the rest to decrease even further via background tasks)
This commit is contained in:
parent
f7a9b2f823
commit
86c7eba10a
25 changed files with 1941 additions and 1560 deletions
|
|
@ -5,36 +5,40 @@ from .models import TradeOffer
|
|||
from cards.models import Card
|
||||
from django.db.models import F
|
||||
from trades.models import TradeOfferHaveCard, TradeOfferWantCard, TradeAcceptance
|
||||
from django.db import transaction
|
||||
|
||||
def validate_and_set_trade_offer_rarity(instance):
|
||||
"""
|
||||
Ensures all cards on both sides share the same rarity and sets the TradeOffer.rarity
|
||||
if it hasn't been set already.
|
||||
Ensures all cards on both sides share the same rarity and sets the TradeOffer's
|
||||
rarity_level and rarity_icon if they haven't been set already.
|
||||
"""
|
||||
# Combine cards from both sides.
|
||||
combined_cards = list(instance.have_cards.all()) + list(instance.want_cards.all())
|
||||
if not combined_cards:
|
||||
return
|
||||
|
||||
# Gather the Rarity instances from the cards.
|
||||
rarities = {card.normalized_rarity for card in combined_cards}
|
||||
rarities = {card.rarity_level for card in combined_cards}
|
||||
if len(rarities) > 1:
|
||||
raise ValidationError("All cards in a trade offer must have the same rarity.")
|
||||
|
||||
# If trade offer's rarity isn't set yet, update it.
|
||||
if instance.rarity is None:
|
||||
instance.rarity = combined_cards[0].normalized_rarity
|
||||
instance.save(update_fields=["rarity"])
|
||||
updated_fields = []
|
||||
if instance.rarity_level is None:
|
||||
instance.rarity_level = combined_cards[0].rarity_level
|
||||
updated_fields.append("rarity_level")
|
||||
if instance.rarity_icon is None:
|
||||
instance.rarity_icon = combined_cards[0].rarity_icon
|
||||
updated_fields.append("rarity_icon")
|
||||
if updated_fields:
|
||||
instance.save(update_fields=updated_fields)
|
||||
|
||||
@receiver(m2m_changed, sender=TradeOffer.have_cards.through)
|
||||
def validate_have_cards_rarity(sender, instance, action, **kwargs):
|
||||
if action == "post_add":
|
||||
validate_and_set_trade_offer_rarity(instance)
|
||||
transaction.on_commit(lambda: validate_and_set_trade_offer_rarity(instance))
|
||||
|
||||
@receiver(m2m_changed, sender=TradeOffer.want_cards.through)
|
||||
def validate_want_cards_rarity(sender, instance, action, **kwargs):
|
||||
if action == "post_add":
|
||||
validate_and_set_trade_offer_rarity(instance)
|
||||
transaction.on_commit(lambda: validate_and_set_trade_offer_rarity(instance))
|
||||
|
||||
ACTIVE_STATES = [
|
||||
TradeAcceptance.AcceptanceState.ACCEPTED,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue