Home > front end >  how to deal with model property in django view
how to deal with model property in django view

Time:03-08

I am trying to do an ecommerce app ,where in i have to add coupon code in the checkout page. I had a model property to check for the coupon code validity.Here is my code

model:

class CoupenCode(models.Model):
code=models.CharField(max_length=100)
startdate=models.DateField()
enddate=models.DateField()
discount=models.IntegerField()
disc_type=models.CharField(max_length=20,choices=(
    ('Amount','Amount'),
    ('Percentage','Percentage')))
usercount=models.PositiveIntegerField()
min_amount=models.PositiveIntegerField()

@property
def is_expired(self):
    if datetime.now().date() > self.enddate or datetime.now().date() < self.startdate :
        return False
    return True

class Meta:
    db_table = 'CoupenCode'
    ordering = ['-id']

def __str__(self):
    return self.code

views:

def fncoupon(request):
if request.method=="POST":
    coupon=request.POST.get('promo')
    couponcode=CoupenCode.objects.filter(code=coupon)
    validity=couponcode.is_expired()
    if validity == True :
        if couponcode.disc_type == "Amount":
            discount=couponcode.discount   'Rs'
        else:
            discount=couponcode.discount   '%'
        print(discount)
        return JsonResponse({'discount':discount})

    else:
        message="This coupon code is not valid"

    print(message)
    return JsonResponse({'message':message})

the problem is i cant check for the coupon code validity using this property in views.it gives me an error

'QuerySet' object has no attribute 'is_expired'

Can anyone please suggest me how i could solve this..

CodePudding user response:

You use .filter(…), but that will return a QuerySet, so a collection of CouponCodes. You should use .get(…) or even better: get_object_or_404(…):

from django.shortcuts import get_object_or_404

def fncoupon(request):
    if request.method == 'POST':
        couponcode = get_object_or_404(CoupenCode, code=request.POST.get('promo'))
        if not couponcode.is_expired:
            if couponcode.disc_type == "Amount":
                discount=couponcode.discount   'Rs'
            else:
                discount=couponcode.discount   '%'
            return JsonResponse({'discount':discount})
        else:
            message='This coupon code is not valid'
        return JsonResponse({'message':message})

It however does not make much sense to do this through a POST request: a POST request typically is used to perform side-effects, whereas a GET is used to retrieve data, here a GET request seems more appropriate.

  • Related