Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Do you query database data in model or view, Django

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading