嗨我想在Django admin Form
中访问字段的值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管理员表格访问该字段。
答案 0 :(得分:0)
这与任何其他Django视图都不同。 MySqlQueryAdmin的实例并不引用任何MySqlQuery实例:它是整个模型类的管理员,而不是它的任何特定实例。这意味着没有办法获得&#34;&#34;查询实例的值,不传递标识符,并使用该标识符从数据库中获取对象。
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,但我想你已经知道了它的风险。