simplyvic
simplyvic

Reputation: 243

How to use for loop variable inside if block

for instance in GratuityPayment.objects.all():
        print instance.date_paid
        if (employment_number == instance.employment_number):
            raise forms.ValidationError('This Employment Mumber was paid on ' + str(instance.date_paid) + '. You cannot proceed with this retirement')

print instance.date_paid in printing all the date_paid that are stored in the database but str(instance.date_paid) is given None.

Am having the following line as my output

This Employment Mumber was paid on None. You cannot proceed with this retirement

How can i use instance.date_paid inside the if statement.

Upvotes: 0

Views: 46

Answers (2)

simplyvic
simplyvic

Reputation: 243

It is actually working. Its Given None because that particular Table row did have None in the table.

I just populated the date_paid and it returned the date instead of None.

Upvotes: 0

alecxe
alecxe

Reputation: 473813

If you want to not apply the check when date_paid is None:

for instance in GratuityPayment.objects.all():
    if instance.date_paid is not None and employment_number == instance.employment_number:
        raise forms.ValidationError('This Employment Mumber was paid on ' + str(instance.date_paid) + '. You cannot proceed with this retirement')

But, why don't use .filter() and get only relevant records in the first place:

GratuityPayment.objects.filter(date_paid__isnull=False, 
                               employment_number=employment_number)

Upvotes: 1

Related Questions