-2

I am wondering form the following functions written in different ways in python. The first function is working fine and success. Return a correct data and successfully delete the record from the database. In the second one, return correct data, but in the database doesn't delete anything!!!. The record which should deleted still exit.

What do you thing the reason that prevent the second function from successfully deleting the record from the database.

Note: I use FLASK SQLAchemy connection to postgress database. The class name is (Movie) and the table name is (movies)

first success function is:

# Creating endpoint to delete a movie by providing movie_id
@app.route('/movies/<int:movie_id>', methods = ['DELETE'])
def delete_movie(movie_id):
    movie = Movie.query.filter(Movie.id == movie_id).one_or_none()

    if movie is None:
        abort(404)  # abort if id is not found
    else:
        try:
            movie.delete()
            # return movie id that was deleted
            return jsonify({
                'success': True,
                'deleted': movie_id
            })
        except Exception:
            abort(422)

The second fail function is:

@app.route('/movies/<int:movie_id>', methods = ['DELETE'])
def delete_movie(movie_id):
    movie = Movie.query.filter(Movie.id == movie_id)
    movie_availability = movie.one_or_none()

    if movie_availability is None:
        abort(404)  # abort if id is not found
    else:
        try:
            movie.delete()
            # return movie id that was deleted
            return jsonify({
                'success': True,
                'deleted': movie_id
            })
        except Exception:
            abort(422)
Khalil
  • 41
  • 1
  • 10

1 Answers1

1

You need to delete movie_availability in your second example not movie.

I.e.

try:
    movie_availability.delete()

In your second example movie_availability becomes the record retrieved from the database, whereas in your first example that's condensed into one line and assigned to movie.

PGHE
  • 1,585
  • 11
  • 20
  • Many thanks for your answer. Now it is clear for me... another thing, why some people they dislike my question. This is strange. What is wrong with my question?!!! I spent three days thinking about this question before I post my question!!! I don't know how those people evaluation my question like this :( – Khalil Aug 26 '20 at 09:26