简体   繁体   中英

How to save() an argument in a Django Model

I am learning Django, and I decided to simulate an ATM. When I run, my code works, and it says that the deposit to the Card was successful, but it does not save it, the original balance stays the same. Here's what I have:

models.py

class Card(models.Model):
    card_number = models.PositiveIntegerField(primary_key=True) 
    #account_number = models.ForeignKey(Account, to_field='account_number',on_delete=models.CASCADE)
    card_name = models.CharField(max_length=30)
    balance = models.PositiveIntegerField() 

    def __str__(self):
        return self.card_name

views.py

def deposit(request):
    if request.method == 'POST':
        user_pin = request.POST.get('Pin')
        user_card_number = request.POST.get('Your Card Number') 
        amount = request.POST.get('Amount')    
            user_balance = Card.objects.get(card_number=user_card_number).balance  
            user_card_name = Card.objects.get(card_number=user_card_number).card_name 

            # performs deposit
            user_balance += int(amount)                
            Card.objects.get(card_number=user_card_number).save()

            messages.success(request, 'Deposit Success! ' + '$'+ amount + ' has been depositted from card: ' + user_card_name)   
        else:
            messages.error(request, 'Card Number or Pin is incorrect')
    return render(request, 'deposit.html')

Now, I tried reading the save() documentation and follow tutorials, but they did not work. So, how can I save the new balance on my card after the deposit is done? Thank you.

you dont need get the Card object everytime you want to access an attribute of the model class.

You can do something like this

card= Card.objects.get(card_number=user_card_number)
card.balance +=int(amount)
card.save()

When you are want to save an update. First thing to do is get the object to be edit.

#gets user pin,balance, card name based on user's card number input
#pin_number = Card.objects.filter(card_number=user_card_number).pin  # error if use this
user_balance = Card.objects.get(card_number=user_card_number).balance  
user_card_name = Card.objects.get(card_number=user_card_number).card_name

You should change that code to

userCardObject = Card.objects.get(card_number=user_card_number)

then you can update the value inside the objects, and save it

userCardObject.balance += int(amount)
userCardObject.save()

What you do on your code just updating value of user_balance but doesn't update the value of row in table(because you don't update the column of balance directly to the object representation of it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM