ytsejam
ytsejam

Reputation: 3439

How to test Nonetype in Python

I am trying to create a model with a upload_photo function using an instance of a class. Before creating my first object I always get error claiming 'NoneType' object has no attribute 'id'.

I checked various answers and solutions, but I still could not find a way to test NoneType for a class. I use version 3.6 of Python 3 and version 1.11 of Django.

Here is my upload function which is used in CFE tutorials:

def upload_location(instance, filename):
    PostModel = instance.__class__
    new_id = PostModel.objects.order_by("id").last().id + 1
    return '{} {}'.format(new_id, filename)

How can I test in the first instance of a class without getting an error?

Upvotes: 2

Views: 378

Answers (1)

Håken Lid
Håken Lid

Reputation: 23064

This error is to be expected if there aren't any objects saved yet.

new_id = PostModel.objects.order_by("id").last().id + 1

It's the same as this:

lastpost = PostModel.objects.order_by("id").last()  # can return None
new_id = lastpost.id + 1  # will error if lastpost is None

To me it seems that raising an error could be the appropriate outcome here. You could catch the error and use a different value.

try:
    new_id = PostModel.objects.order_by("id").last().id + 1
except AttributeError:  # no posts in database
    new_id = 1

Be advised that you should not use this method to assign primary keys to your database instances, as several have already commented. You should let the database do that for you if you want to avoid data loss and messy bugs.

This is also the default behaviour in Django.

By default, Django gives each model the following field:

id = models.AutoField(primary_key=True)

This is an auto-incrementing primary key.

https://docs.djangoproject.com/en/1.11/topics/db/models/#automatic-primary-key-fields

Upvotes: 2

Related Questions