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):
        ##SM:added
        ##we can't call obj.save() (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.book.id, obj.year, obj.user.id, obj.bookstatus))
        transaction.commit_unless_managed()      
        objs = core_m.UserBookStatus.objects.filter(user=obj.user).filter(year=obj.year).filter(book=obj.book).all()
        if objs:
            obj = objs[0]
        return obj



No comments:

Post a Comment