0

I have an app that was built in Django. And I want to use direct SQL Queries to access my MySQL Database. So far, this are my codes

models.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'

views.py

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)

It works really fine but is there any way that I can access database and do some process Like SELECT , UPDATE or DELETE without using my models.py ?

  • 1
    if so why would you use Django then ? – cizario Oct 09 '20 at 17:34
  • without using models.py? I dont know what your idea of django is but models.py is just to structure your db and add fields to tables. You can use rawsql or the django orm it is irrelevant.Yes can uodate and delete and whatever using sql but this has nothing to do with the models.py. you dont even need objects.raw just connect directly with the db https://stackoverflow.com/questions/14209868/how-to-work-with-sqlite3-and-python if you dont want to use the orm at all – hansTheFranz Oct 09 '20 at 17:39
  • Yah that's what i'm thinking about. My boss wants me to use this kind of process for future like we can just put the databse credentials and access it without migrating to django models –  Oct 09 '20 at 18:09
  • Exactly *why* do you want to use direct queries. You can work with *unmanaged* tables. But all these direct queries will cause more pain than gain. Django queries try to prevent SQL injection, make it easier to make abstraction of the underlying database technology, and make changing a table, for example renaming a field, less painful. – Willem Van Onsem Oct 09 '20 at 18:11

0 Answers0