Home > Mobile >  Display 1 when no data is exist in database
Display 1 when no data is exist in database

Time:07-15

I am trying to generate incremental id whenever I am adding new data in my model. here I am getting the the next number whenever I am adding new data. but If there is no any data in my table its giving me error. 'NoneType' object has no attribute 'tax_id'

Here is my code

views.py

def tax_settings(request):
latest_id = (Tax_Settings.objects.last()).tax_id 1
if request.method == 'POST':
    tax_id = latest_id
    name = request.POST['tax_name']
    tax_percentage = request.POST['tax_percentage']
    tax_details=Tax_Settings.objects.create(tax_id=tax_id, name=name, tax_percentage=tax_percentage)
    tax_details.save()
    next_id = (Tax_Settings.objects.last()).tax_id 1
    return render(request,"settings/tax-settings.html",{"latest_id":next_id})
else:
    return render(request,"settings/tax-settings.html",{"latest_id":latest_id})

html

<input type="text"  placeholder="{{latest_id}}" name="tax_id"  disabled>

which condition I can give to my latest_id if data(tax_id) not exists?

CodePudding user response:

You are trying to do too much in too few lines of code. Wherever you use queryset .last() or .first() you must explicitly handle the case where it returns None!

You need code of the form:

o = Tax_Settings.objects.last()
if o is not None:
    tax_id = o.tax_id   1
else:
    tax_id = 1 # if that's a sensible default value

or even

o = Tax_Settings.objects.last()
assert o is not None, "This can't happen!" # except obviously, it does in this question.

CodePudding user response:

Either you first create a single record than don't need to handle this or

tax_id = 0
latest_rec = (Tax_Settings.objects.last())
if latest_rec is not None:
    latest_id = latest_rec.tax_id 1

CodePudding user response:

You could simply add:

if latest_id is None:
    latest_id = 1

CodePudding user response:

If I understand it correctly, you have issues with your first line in the provided function:
latest_id = Tax_Settings.objects.last().tax_id 1

when you have no data, i.e. Tax_Settings.objects.last() is None.

You should define default ID, for instance 0 which would be assigned in case of missing objects:

def tax_settings(request):
    if Tax_Settings.objects.last() is not None:
        # some data already stored
        latest_id = Tax_Settings.objects.last().tax_id
    else:
        # no data present yet
        latest_id = 0
    . . .

btw. I am not sure why are you incrementing the latest value in the beginning, but you need to take into account that if your default latest ID is 0 then the ID of the first data unit stored will be 1.

CodePudding user response:

The following code also works:

tax_data=Tax_Settings.objects.all()
    if not tax_data:
        print("no data found")
        latest_id=1
    else:
        latest_id = (Tax_Settings.objects.last()).tax_id 1
  • Related