2014-08-28 107 views
0

您好我想訪問Django管理表單字段的值訪問模型場admin.ModelAdmin在Django

model.py

from __future__ import absolute_import, division 
from django.db import models 
from django.utils.encoding import python_2_unicode_compatible 
@python_2_unicode_compatible 
class MySqlQuery(models.Model): 
    name = models.CharField(max_length=100) 
    query = models.TextField(max_length=1000) 

    class Meta: 
     verbose_name = 'SQL Query' 
     verbose_name_plural = 'SQL Queries' 
    def __str__(self): 
     return self.name 

admin.py

class MySqlQueryAdmin(admin.ModelAdmin): 

    list_display = ('query', 'name', 'action') 

    def get_urls(self): 
     urls = super(MySqlQueryAdmin, self).get_urls() 
     my_urls = patterns('', url(r"^execute/$", 
         self.admin_site.admin_view(self.execute_query))) 
     return my_urls + urls 

    def execute_query(self, request): 
     cursor = connection.cursor() 
     try: 
     #------------------------------------------ 
     #need to access query field from the models 
     #------------------------------------------ 
     cursor.execute(self.form.query) 
     except: 
     logger.error('query was not right') 
     finally: 
     cursor.close() 

     return HttpResponseRedirect(request.META['HTTP_REFERER']) 

    def action(self, form): 
     return "<a href='execute/'>execute</a>" 

    action.allow_tags = True 


admin.site.register(MySqlQuery, MySqlQueryAdmin) 

我創建了一個models.py,它有字段查詢,我想從Django管理員執行查詢。爲此,我需要訪問django admin表單中的字段。

回答

0

這與其他Django視圖沒有區別。 MySqlQueryAdmin的實例沒有引用任何MySqlQuery實例:它是整個模型類的管理員,而不是任何特定的實例。這意味着如果不傳遞標識符並使​​用該標識符從數據庫獲取對象,就無法獲得查詢實例的「值」。

class MySqlQueryAdmin(admin.ModelAdmin): 

    list_display = ('query', 'name', 'action') 

    def get_urls(self): 
     urls = super(MySqlQueryAdmin, self).get_urls() 
     my_urls = patterns('', url(r"^execute/(?P<id>\d+)/$", 
         self.admin_site.admin_view(self.execute_query), name="execute")) 
     return my_urls + urls 

    def execute_query(self, request, id): 
     query = MySqlQuery.objects.get(id=id) 
     ... 

    def action(self, obj): 
     return "<a href='%s'>execute</a>" % reverse(admin:execute, kwargs={'id': obj.id}) 
    action.allow_tags = True 

當然,我不建議做這樣的任何東西,因爲你似乎可以執行任意用戶提供對SQL數據庫,但我想你已經知道的是風險。

+0

感謝您的回答,但我已經知道了。你如何讓遊標只執行只讀查詢? – 2014-08-28 09:03:05