codingforentrepreneurs / Blog-API-with-Django-Rest-Framework

Blog API with Django Rest Framework
MIT License
357 stars 173 forks source link

Base case for creating new posts on a clean DB has not been handled. #8

Open Arnie09 opened 4 years ago

Arnie09 commented 4 years ago

models.py in posts app.

replace the exiting upload_location function with this code snippet. I have already ported my db to Postgres, hence I ain't making a pull request.

def upload_location(instance, filename):
     #filebase, extension = filename.split(".")
     #return "%s/%s.%s" %(instance.id, instance.id, extension)
     PostModel = instance.__class__
     last = PostModel.objects.order_by("id").last()
     new_id = 1 if last == None else (last.id+1)

    """
    instance.__class__ gets the model Post. We must use this method because the model is defined below.
    Then create a queryset ordered by the "id"s of each object, 
    Then we get the last object in the queryset with `.last()`
    Which will give us the most recently created Model instance
    We add 1 to it, so we get what should be the same id as the the post we are creating.
    """
    return "%s/%s" %(new_id, filename)