Custom Search

Thursday, August 21, 2014

Django ModelAdmin save object without using Django ORM

* Override the "save_model" method of "admin.ModelAdmin"
* Use connection and transaction

from django.db import connection, transaction

class StatusAdmin(admin.ModelAdmin)

    def save_model(self, request, obj, form, change):
        ##we can't call (we can't use save_model of base class) since the model class definition
        ##of "UserBookStatus" has a primary key column named "book", and in database that is not a primary key.
        cursor = connection.cursor()
        cursor.execute("insert into userbookstatus (indexbookid, year, userid, bookstatus) values (%s,%s,%s,'%s')"\
                         %(, obj.year,, obj.bookstatus))
        objs = core_m.UserBookStatus.objects.filter(user=obj.user).filter(year=obj.year).filter(
        if objs:
            obj = objs[0]
        return obj

No comments:

Post a Comment