Add rarity field to trade_offer instead of looking up via cards
This commit is contained in:
parent
ba33139993
commit
f7a9b2f823
13 changed files with 87 additions and 50 deletions
|
|
@ -6,22 +6,35 @@ from cards.models import Card
|
|||
from django.db.models import F
|
||||
from trades.models import TradeOfferHaveCard, TradeOfferWantCard, TradeAcceptance
|
||||
|
||||
def check_trade_offer_rarity(instance):
|
||||
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.
|
||||
"""
|
||||
# Combine cards from both sides.
|
||||
combined_cards = list(instance.have_cards.all()) + list(instance.want_cards.all())
|
||||
# Use the normalized rarity from each card
|
||||
if not combined_cards:
|
||||
return
|
||||
|
||||
# Gather the Rarity instances from the cards.
|
||||
rarities = {card.normalized_rarity 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"])
|
||||
|
||||
@receiver(m2m_changed, sender=TradeOffer.have_cards.through)
|
||||
def validate_have_cards_rarity(sender, instance, action, **kwargs):
|
||||
if action == "post_add":
|
||||
check_trade_offer_rarity(instance)
|
||||
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":
|
||||
check_trade_offer_rarity(instance)
|
||||
validate_and_set_trade_offer_rarity(instance)
|
||||
|
||||
ACTIVE_STATES = [
|
||||
TradeAcceptance.AcceptanceState.ACCEPTED,
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue