Answer the question
In order to leave comments, you need to log in
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
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')
Answer the question
In order to leave comments, you need to log in
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
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 questionAsk a Question
731 491 924 answers to any question