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表單中的字段。
感謝您的回答,但我已經知道了。你如何讓遊標只執行只讀查詢? – 2014-08-28 09:03:05