Как установить лимит на вывод средств? Django, Python

У меня есть проект, где пользователи пополняют счет, играют в игру и снимают деньги. Я хочу установить лимит на вывод средств для определенных групп пользователей.

это моя модель пользователя:

class User(AbstractBaseUser, PermissionsMixin):
 class PlatformStatus(models.TextChoices):
    NOT_REQUESTED = 'not requested'
    REQUESTED = 'requested'
    PENDING = 'pending'
    CREATED = 'created'

class Status(models.TextChoices):
    PENDING = 'pending'
    ACTIVE = 'active'
    DEACTIVATED = 'deactivated'
    BLACK_LIST = 'blacklist'

class UserRole(models.TextChoices):
    REGULAR = 'regular'
    SILVER = 'silver'
    GOLD = 'gold'
    PLATINUM = 'platinum'
    VIP = 'vip'

class ReadStatus(models.TextChoices):
    READ = 'read'
    UNREAD = 'unread'
    ACTIVE = 'active'

"""" Custom user model that uses email instead of username """
id = models.AutoField(primary_key=True, editable=False)
email = models.EmailField(max_length=255, unique=True)
username = models.CharField(max_length=255, unique=True, null=True, blank=True)
is_staff = models.BooleanField(default=False)
is_active = models.BooleanField(default=False)
status = models.CharField(max_length=250, choices=Status.choices, default="pending")
role = models.CharField(max_length=250, choices=UserRole.choices, default='regular')
created_at = models.DateTimeField(auto_now_add=True, null=True)
first_name = models.CharField(max_length=150, unique=False, null=True)
last_name = models.CharField(max_length=150, unique=False, null=True)
phone = models.CharField(max_length=20, unique=True, null=True, blank=False)
user_ip = models.CharField(max_length=120, null=True, blank=False)
is_phone_verified = models.BooleanField(default=False)
is_id_verified = models.BooleanField(default=False)
id_number = models.CharField(max_length=250, unique=True, null=True)
id_issued_state = models.CharField(max_length=250, null=True)
id_self = CompressedImageField(upload_to="user-id/self/", null=True, default=None, max_length=500, quality=50,
                               validators=[validate_file])
id_front = CompressedImageField(upload_to="user-id/front/", null=True, default=None, max_length=500, quality=50,
                                validators=[validate_file])
id_back = CompressedImageField(upload_to="user-id/back/", null=True, default=None, max_length=500, quality=50,
                               validators=[validate_file])
btc_address = models.CharField(max_length=500, unique=True, null=True, blank=True)
referral_code = models.CharField(max_length=10, blank=True)
referred_user = models.CharField(max_length=300, blank=True, null=True)
total_spent = models.DecimalField(max_digits=7, decimal_places=2, null=True, default=0.00, blank=True)
total_withdrawals = models.DecimalField(max_digits=20, decimal_places=2, null=True, default=0.00, blank=True)
total_withdrawal_count = models.IntegerField(default=0, blank=True, null=True)

а это модель WithdrawRequest:


class WithdrawRequest(models.Model):
    class WithdrawStatus(models.TextChoices):
        PENDING = 'pending'
        PROCESSED = 'processed'
        DECLINED = 'declined'
        PROCESSING = 'processing'

    class ReadStatus(models.TextChoices):
        READ = 'read'
        UNREAD = 'unread'
        ACTIVE = 'active'

    _id = models.AutoField(primary_key=True, editable=False)
    uuid = models.UUIDField(default = uuid.uuid4, editable = False)
    user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
    user_email = models.CharField(max_length=400, null=True, blank=True)
    platform = models.CharField(max_length=250, null=True)
    amount = models.DecimalField(max_digits=7, decimal_places=2, null=True)
    btc_address = models.CharField(max_length=500, null=True, blank=True)
    phone = models.CharField(max_length=20, null=True, blank=False)
    created_at = models.DateTimeField(auto_now_add=True, null=True)
    message = models.TextField(blank=True, null=True)
    note = models.TextField(blank=True, null=True)
    status = models.CharField(max_length=250, choices=WithdrawStatus.choices, default="pending")
    read_status = models.CharField(max_length=250, choices=ReadStatus.choices, default="unread")

    def __str__(self):
        return str(self._id)

И это мое мнение:

 @api_view(['POST'])
 @permission_classes([IsAuthenticated, HasWhitelistedIp])
 def check_withdrawal_limit(request):
    data = request.data
    time_24_hours_ago = datetime.datetime.now() - datetime.timedelta(days=1)
    user = User.objects.get(id=data["id"])
    withdrawals = user.withdrawrequest_set.all().filter(created_at__gte=time_24_hours_ago).aggregate(Sum('amount'))
    
    for w in withdrawals:
        if user.role == "regular":
            int(float(w)) <= 250
        elif user.role == "silver":
            int(float(w)) <= 500
        elif user.role == "gold":
            int(float(w)) <= 1000
        elif user.role == "diamond":
            int(float(w)) <= 2500
        else:
            raise ValidationError("You have exceeded your withdrawal limit")

    return Response(withdrawals["amount__sum"])

Я получаю ошибку "ValueError: could not convert string to float: 'amount__sum'". Может у вас есть идеи как заставить это работать?

Вернуться на верх