Python 使用直接SQL查询访问Django中的数据库
我有一个应用程序是在Django中构建的。我想使用直接SQL查询来访问我的MySQL数据库。到目前为止,这是我的代码 型号.pyPython 使用直接SQL查询访问Django中的数据库,python,mysql,django,mysql-workbench,Python,Mysql,Django,Mysql Workbench,我有一个应用程序是在Django中构建的。我想使用直接SQL查询来访问我的MySQL数据库。到目前为止,这是我的代码 型号.py class FillWeight(models.Model): weight_description = models.CharField(max_length=100, blank=True, null=True) filler_operator = models.CharField(max_length=100, blank=True, null=
class FillWeight(models.Model):
weight_description = models.CharField(max_length=100, blank=True, null=True)
filler_operator = models.CharField(max_length=100, blank=True, null=True)
weight_date = models.DateField(auto_now_add= False, blank=True, null=True)
start_time = models.TimeField(auto_now_add = False, blank=True, null=True)
finish_time = models.TimeField(auto_now_add = False,blank=True, null=True)
class Meta:
db_table = 'fill_weight'
def show_list_of_info(request):
template_name = 'oof_ord/homepage.html'
list = FillWeight.objects.raw('SELECT * FROM fill_weight WHERE id = 1')
context = {
'list':list
}
return render(request, template_name, context)
视图.py
class FillWeight(models.Model):
weight_description = models.CharField(max_length=100, blank=True, null=True)
filler_operator = models.CharField(max_length=100, blank=True, null=True)
weight_date = models.DateField(auto_now_add= False, blank=True, null=True)
start_time = models.TimeField(auto_now_add = False, blank=True, null=True)
finish_time = models.TimeField(auto_now_add = False,blank=True, null=True)
class Meta:
db_table = 'fill_weight'
def show_list_of_info(request):
template_name = 'oof_ord/homepage.html'
list = FillWeight.objects.raw('SELECT * FROM fill_weight WHERE id = 1')
context = {
'list':list
}
return render(request, template_name, context)
它工作得很好,但有没有任何方法可以让我访问数据库并执行一些过程,如
选择,更新或删除,而不使用我的models.py?如果有,为什么要使用Django?不使用models.py?我不知道你对django的想法是什么,但是models.py只是构造数据库并向表中添加字段。您可以使用rawsql或django-orm,这是不相关的。是的,您可以使用sql进行数据更新和删除以及其他操作,但这与models.py无关。你甚至不需要objects.raw,如果你根本不想使用orm,就直接连接数据库吧,这就是我想的。我的老板希望我在将来使用这种过程,就像我们可以只放置数据库凭据并访问它,而无需迁移到django模型。实际上,为什么要使用直接查询。您可以使用非托管表。但是,所有这些直接的查询将带来更多的痛苦而不是收获。Django查询试图阻止SQL注入,使底层数据库技术的抽象变得更容易,并使更改表(例如重命名字段)变得更轻松。