Home > Blockchain >  Do you query database data in model or view, Django
Do you query database data in model or view, Django

Time:10-23

This is probably a dumb question here but bran new to Python/Django.

I've worked with many other frameworks and how the MVC works is in the model is where you make all your queries and then you grab them from the controller to send to the view.

In Django it's telling me to make these queries in the view.py file(a controller in other frameworks)

Example:

Models.py

from django.db import models


    class Moves(models.Model):
        name = models.CharField(max_length=64)
        description = models.CharField(max_length=500)
        position_id = models.IntegerField()
        is_offence = models.BooleanField(default=True)

views.py

def half_guard_moves(request):

    half_guard_moves = Moves.objects.values().filter(position_id=2)

    return render(request, "moves/halfguardmoves.html", {'half_guard_moves': half_guard_moves})

This works but seems odd because I'm actually making the query in the views(controller) file not the model? Am I doing this correct or is there another way to make queries directly in the model?

CodePudding user response:

According to Django's documentation the models.py file's purpose is to only declare tables. For example

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

This file would create the following SQL command:

CREATE TABLE myapp_person (
    "id" bigint NOT NULL PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

Answering your question. No there are no queries made in the declaration of models, you make the queries in the views.py to retrieve instances as neccesary.

  • Related