A
A
aLap2021-09-08 12:40:46
Django
aLap, 2021-09-08 12:40:46

How to get data from Django model?

I decided to use Django for one small project, I encountered this framework for the first time.
The essence of the question is that I can not get data from the database in accordance with the documentation.

models.py

from django.db import models
from django.contrib.auth.models import User


class Number(models.Model):
    number = models.BigIntegerField(unique=True)
    description = models.CharField(max_length=255)
    account_id = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)

    def __str__(self):
        return '%s' % self.number


views.py

from django.http import HttpResponse, HttpResponseRedirect
from .models import Number


def index(request):
    from django.contrib.auth import get_user
    user = get_user(request)
    numbers = Number.objects.all()
    if user.is_authenticated:
        return HttpResponse(numbers)
    else:
        return HttpResponseRedirect('/login')


A direct query to the database returns everything correctly:

select id,number from clients_number;
+----+---------+
| id | number |
+----+---------+
| 2 | 2193333 |
| 3 | 2193336 |
+----+---------+

Another problem is that the IDE does not see the objects attribute to the model point-blank, that is, in the Number.objects line, the objects attribute is highlighted as non-existent. I did everything according to the documentation.
Python 3.6
Django 3.2.6

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stefan, 2021-09-08
@aLap

First: objects will be highlighted, and since they do not exist, since they do not exist directly in the model classes and in those from which it is inherited, there is a tricky mechanism, and it is injected into the class later, so it is highlighted as non-existent, but it is (In PyCharm proffesional everything will be ok, because the IDE developers have written everything manually there)
Second: What does it mean that you can’t get the data, you checked the numbers variable at least with a print, if the data does not come to the client, then this is not because they are not there, but because you are trying to shove a python object in the HttpResponse, when it receives a string or bytes, serialize your object and only then send it

A
Alexander Nesterov, 2021-09-08
@AlexNest

Specifically, if you need to give all the data at once, without formatting, then here .
(Though, if you need a lot of similar views, I would advise you to pay attention to the django rest framework)
Otherwise, use templates.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question