# Buggy code
def after_create_object(self, order, data, view_kwargs):
    """
    after create object method for OrderListPost Class
    :param order:
    :param data:
    :param view_kwargs:
    :return:
    """
    order_tickets = {}
    for holder in order.ticket_holders:
        if holder.id != current_user.id:
            pdf = create_save_pdf(
                render_template("/pdf/ticket_attendee.html", order=order, holder=holder)
            )
        else:
            pdf = create_save_pdf(
                render_template("/pdf/ticket_purchaser.html", order=order)
            )
        holder.pdf_url = pdf
        save_to_db(holder)
        if order_tickets.get(holder.ticket_id) is None:
            order_tickets[holder.ticket_id] = 1
        else:
            order_tickets[holder.ticket_id] += 1
    for ticket in order_tickets:
        od = OrderTicket(
            order_id=order.id, ticket_id=ticket, quantity=order_tickets[ticket]
        )
        save_to_db(od)
    order.quantity = order.get_tickets_count()
    save_to_db(order)
    if not has_access("is_coorganizer", event_id=data["event"]):
        TicketingManager.calculate_update_amount(order)
    send_email_to_attendees(order, current_user.id)
    send_notif_to_attendees(order, current_user.id)

    order_url = make_frontend_url(
        path="/orders/{identifier}".format(identifier=order.identifier)
    )
    for organizer in order.event.organizers:
        send_notif_ticket_purchase_organizer(
            organizer, order.invoice_number, order_url, order.event.name
        )

    data["user_id"] = current_user.id


# Traceback (psycopg2.IntegrityError)
(psycopg2.IntegrityError) insert or update on table "notifications" violates foreign key constraint "notifications_user_id_fkey"
DETAIL:  Key (user_id)=(5) is not present in table "users".
[SQL: 'INSERT INTO notifications (user_id, title, message, action, received_at, is_read) VALUES (%(user_id)s, %(title)s, %(message)s, %(action)s, %(received_at)s, %(is_read)s) RETURNING notifications.id'] [parameters: {'user_id': 5, 'title': 'Your ticket for Main Event', 'message': "Your order has been processed successfully.<br><br><a href='http://127.0.0.1:5000/static/media/attendees/tickets/pdf/5566d5b7-bfb8-43f1-a834-a851ac45ede1/YXU5RWJWcT/c4438374-d5dd-46a5-bac2-c21695370d47.pdf' class='btn btn-info btn-sm'>View PDF</a>", 'action': 'Ticket Purchased to Attendee', 'received_at': datetime.datetime(2018, 6, 20, 11, 12, 16, 856225, tzinfo=<UTC>), 'is_read': False}]
Traceback (most recent call last):
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
psycopg2.IntegrityError: insert or update on table "notifications" violates foreign key constraint "notifications_user_id_fkey"
DETAIL:  Key (user_id)=(5) is not present in table "users".


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
File "/media/srv_twry/work/Projects/Community-Projects/Fossasia/open-event-server/app/api/helpers/db.py", line 24, in save_to_db
db.session.commit()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/scoping.py", line 157, in do
return getattr(self.registry(), name)(*args, **kwargs)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 921, in commit
self.transaction.commit()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 461, in commit
self._prepare_impl()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 441, in _prepare_impl
self.session.flush()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2192, in flush
self._flush(objects)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2312, in _flush
transaction.rollback(_capture_exception=True)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/util/langhelpers.py", line 66, in __exit__
compat.reraise(exc_type, exc_value, exc_tb)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 187, in reraise
raise value
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/session.py", line 2276, in _flush
flush_context.execute()
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 389, in execute
rec.execute(self)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/unitofwork.py", line 548, in execute
uow
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 181, in save_obj
mapper, table, insert)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/orm/persistence.py", line 835, in _emit_insert_statements
execute(statement, params)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 945, in execute
return meth(self, multiparams, params)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/sql/elements.py", line 263, in _execute_on_connection
return connection._execute_clauseelement(self, multiparams, params)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1053, in _execute_clauseelement
compiled_sql, distilled_params
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1189, in _execute_context
context)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1402, in _handle_dbapi_exception
exc_info
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 203, in raise_from_cause
reraise(type(exception), exception, tb=exc_tb, cause=cause)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/util/compat.py", line 186, in reraise
raise value.with_traceback(tb)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1182, in _execute_context
context)
File "/home/srv_twry/anaconda3/envs/open-event-server/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 470, in do_execute
cursor.execute(statement, parameters)
sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) insert or update on table "notifications" violates foreign key constraint "notifications_user_id_fkey"
DETAIL:  Key (user_id)=(5) is not present in table "users".
[SQL: 'INSERT INTO notifications (user_id, title, message, action, received_at, is_read) VALUES (%(user_id)s, %(title)s, %(message)s, %(action)s, %(received_at)s, %(is_read)s) RETURNING notifications.id'] [parameters: {'user_id': 5, 'title': 'Your ticket for Main Event', 'message': "Your order has been processed successfully.<br><br><a href='http://127.0.0.1:5000/static/media/attendees/tickets/pdf/5566d5b7-bfb8-43f1-a834-a851ac45ede1/YXU5RWJWcT/c4438374-d5dd-46a5-bac2-c21695370d47.pdf' class='btn btn-info btn-sm'>View PDF</a>", 'action': 'Ticket Purchased to Attendee', 'received_at': datetime.datetime(2018, 6, 20, 11, 12, 16, 856225, tzinfo=<UTC>), 'is_read': False}]
ERROR:root:DB Exception! (psycopg2.IntegrityError) insert or update on table "notifications" violates foreign key constraint "notifications_user_id_fkey"
DETAIL:  Key (user_id)=(5) is not present in table "users".
[SQL: 'INSERT INTO notifications (user_id, title, message, action, received_at, is_read) VALUES (%(user_id)s, %(title)s, %(message)s, %(action)s, %(received_at)s, %(is_read)s) RETURNING notifications.id'] [parameters: {'user_id': 5, 'title': 'Your ticket for Main Event', 'message': "Your order has been processed successfully.<br><br><a href='http://127.0.0.1:5000/static/media/attendees/tickets/pdf/5566d5b7-bfb8-43f1-a834-a851ac45ede1/YXU5RWJWcT/c4438374-d5dd-46a5-bac2-c21695370d47.pdf' class='btn btn-info btn-sm'>View PDF</a>", 'action': 'Ticket Purchased to Attendee', 'received_at': datetime.datetime(2018, 6, 20, 11, 12, 16, 856225, tzinfo=<UTC>), 'is_read': False}]

# Fixed code
def after_create_object(self, order, data, view_kwargs):
    """
    after create object method for OrderListPost Class
    :param order:
    :param data:
    :param view_kwargs:
    :return:
    """
    order_tickets = {}
    for holder in order.ticket_holders:
        if holder.id != current_user.id:
            pdf = create_save_pdf(
                render_template("/pdf/ticket_attendee.html", order=order, holder=holder)
            )
        else:
            pdf = create_save_pdf(
                render_template("/pdf/ticket_purchaser.html", order=order)
            )
        holder.pdf_url = pdf
        save_to_db(holder)
        if not order_tickets.get(holder.ticket_id):
            order_tickets[holder.ticket_id] = 1
        else:
            order_tickets[holder.ticket_id] += 1
    for ticket in order_tickets:
        od = OrderTicket(
            order_id=order.id, ticket_id=ticket, quantity=order_tickets[ticket]
        )
        save_to_db(od)
    order.quantity = order.get_tickets_count()
    save_to_db(order)
    if not has_access("is_coorganizer", event_id=data["event"]):
        TicketingManager.calculate_update_amount(order)
    send_email_to_attendees(order, current_user.id)
    send_notif_to_attendees(order, current_user.id)

    order_url = make_frontend_url(
        path="/orders/{identifier}".format(identifier=order.identifier)
    )
    for organizer in order.event.organizers:
        send_notif_ticket_purchase_organizer(
            organizer, order.invoice_number, order_url, order.event.name
        )

    data["user_id"] = current_user.id