Django serializer returns empty list - python

I have a class-based view that returns all the data in the table. But while accessing the URL all I get is an empty list.
models.py
from django.db import models
class EmployeeModel(models.Model):
EmpID = models.IntegerField(primary_key=True)
EmpName = models.CharField(max_length=100)
Email = models.CharField(max_length=100)
Salary = models.FloatField()
class Meta:
verbose_name = 'employeetable'
views.py
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import EmployeeModel
from .serializers import EmployeeSerialize
class EmployeeTable(APIView):
def get(self,request):
emp_obj = EmployeeModel.objects.all()
empserializer = EmployeeSerialize(emp_obj,many=True)
return Response(empserializer.data)
serializers.py
from rest_framework import serializers
from .models import EmployeeModel
class EmployeeSerialize(serializers.ModelSerializer):
class Meta:
model = EmployeeModel
fields = '__all__'
urls.py
from django.contrib import admin
from django.urls import path, include
from .views import EmployeeTable, transformer_list
urlpatterns = [
path('display/',EmployeeTable.as_view()),
]
The table has 5 rows. It is not empty.
I want to serialize all 5 rows

I have also created the same but in my case, it worked see the below images
See my serializer
See my models below
and my output is here below
I think there are some issue at your code or some mistake can be there can you please provide full information

Related

Django : HttpRequest.__init__() takes 1 positional argument but 2 were given

So I simply want when I click on the particular article to output its slug, for example if the slug of the given article is django-rules then i want it to be outputted as django-rules when i click on it. just that
here is my model
from django.db import models
# Create your models here.
class Article(models.Model):
title = models.CharField(max_length=100)
slug = models.SlugField()
body = models.TextField()
date = models.DateTimeField(auto_now_add = True)
#add in tubnail and author later
def __str__(self):
return self.title
def snippet(self):
return self.body[:50]+'...'
Here is my views.py
from datetime import date
from django.shortcuts import render
from .models import Article
from django.http import HttpRequest
# Create your views here.
def article_list(request):
articles = Article.objects.all().order_by('date')
return render(request,'articles/article_list.html', {'articles': articles} )
def article_detail(request, slug):
return HttpRequest(slug)
url.py
from posixpath import relpath
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
app_name = 'articles'
urlpatterns = [
path('', views.article_list, name = 'list'),
path('<slug:slug>/', views.article_detail, name = 'detail'),
]
Please dont suggest to add as_view()
its not working.
Instead of return HttpRequest(slug), you need to return HttpResponse(slug).

Django how to get one result using slicing queryset

I have to fetch the usernames of my authors' posts
Here the views.py:
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpResponse
from django.forms import inlineformset_factory
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth import authenticate,login,logout
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from .forms import CreateUserForm
from .models import Post
from .forms import PostForm
def counter(request):
authors = Post.objects.values_list('author', 'title')
authors_id = Post.objects.values_list('author')
authors_name = User.objects.get(id=authors_id)
context = {'authors':authors, 'authors_name':authors_name}
return render(request, 'account/counter.html', {'authors': authors})
My models.py is:
from django.db import models
from django.conf import settings
from django.utils import timezone
# Create your models here.
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
And here my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from .models import Post
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email','password1','password2','user_permissions','is_staff','date_joined']
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ['title', 'text', 'author']
Now the problem is that on 'authors_id' I have this Error: The QuerySet value for an exact lookup must be limited to one result using slicing, or if i get just one result value of the list the answer's error is: Field 'id' expected a number but got (3,).
So because it takes also the comma from 'values_list'.
I've to got back each author's post and the title of each post the author wrote.
How can I slice the queryset's list?
try this
authors_id = Post.objects.values_list('author', flat=True)
authors_name = User.objects.get(id__in=authors_id)
or
authors_id = Post.objects.values_list('author', flat=True)[0]
authors_name = User.objects.get(id=authors_id)
Refer this https://docs.djangoproject.com/en/3.1/topics/db/queries/#the-pk-lookup-shortcut

Rest_framework import issue

Iam trying to implement django rest framework. I am having this error:
File "F:\....\urls.py", line 19, in <module>
from Userinfo import views
File "F:\....\Userinfo\views.py", line 8, in <module>
from .serializers import usersSerializer
File "F:\.....\Userinfo\serializers.py", line 2, in <module>
from rest_framework import users
ImportError: cannot import name 'users' from 'rest_framework' (C:\Users\....\rest_framework\__init__.py)
My urls.py code:
from django.contrib import admin
from django.urls import path, include
from rest_framework.urlpatterns import format_suffix_patterns
from Userinfo import views
urlpatterns = [
path('admin/', admin.site.urls),
path('api-auth/', include('rest_framework.urls')),
path('UserData', views.UserList.as_view()),
]*
my views.py code:
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .models import users
from .serializers import usersSerializer
class UserList(APIView):
def get(self, request):
user1 = users.objects.all()
serializer = usersSerializer(user1, many = True)
return Response(serializer.data)*
my serializers.py code:
from rest_framework import serializers
from rest_framework import users
class usersSerializer(Serializers.ModelSerializer):
class Meta:
model = users
fields = '__all__'*
my models.py code:
from django.db import models
class users(models.Model):
Name = models.CharField(max_length=50)
id = models.IntegerField(primary_key=True)
DocumentCount = models.IntegerField()
Role = models.CharField(max_length=15)
def _str_(self):
return self.name + self.id*
The code might be incomplete but I'll provide as much information as possible.
In your serializers.py:
from rest_framework import serializers
# from rest_framework import users # remove this
from django.contrib.auth import get_user_model # add this
User = get_user_model()
class usersSerializer(Serializers.ModelSerializer):
class Meta:
model = Users
# model = get_user_model() # this will work too
fields = '__all__'

Show objects on APIView

I have a model, and I just want to show the data of the model in my /api/
from django.db import models
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User
class Book(models.Model):
order_id = models.IntegerField()
isbn = models.IntegerField()
publisher = models.CharField(max_length=256)
school = models.CharField(max_length=256)
price = models.IntegerField()
duration = models.CharField(max_length=10)
order_datetime = models.DateTimeField(auto_now=False, auto_now_add=False)
def __str__(self):
return str(self.order_id)
This is my urls.py:
from django.contrib import admin
from django.urls import path
from filter import views
urlpatterns = [
path('', views.index, name='index'),
path('api/', views.BookApiView.as_view(), name='book_api'),
path('admin/', admin.site.urls),
]
This is my views.py:
from django.shortcuts import render
from rest_framework.views import APIView
from .models import Book
from django.http import JsonResponse
class BookApiView(APIView):
def get(self, request, format=None):
books = Book.objects.all()
return JsonResponse({'model': list(books)})
I get the following error: 'Object of type 'Book' is not JSON serializable'
Regards,
Anthony
Django models can't be JSON serialized implicitly.
You need a serializer to convert the model into a representation that is JSON serializable (primitive dicts, lists, numbers, strings, etc)
Django rest framework serializer docs: http://www.django-rest-framework.org/api-guide/serializers/
class BookSerializer(serializers.Serializer):
order_id = serializers.IntegerField()
isbn = serializers.CharField()
...
class BookApiView(APIView):
def get(self, request, format=None):
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return JsonResponse({'model': serializer.data})
Man... You need a 'Serializer' before send the data to the view!
The Serializez class get the abstract data from the django ORM and parse the data easily to JSON.
Create a file serializers.py at the same level of view.py
and:
from rest_framework import serializers
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
After you create the SerializerBook class, import this on your view and pass the book queryset as the first parameter of the BookSerializer.
...
class BookApiView(APIView):
def get(self, request, format=None):
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
You should define serializer to convert the model instance data to respective JSON data, So define a serializer.py as below
class BookSerializer(serializers.ModelSerializer):
class Meta:
fields = '__all__'
model = Book
then in your view, change as below,<br>
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book
class BookApiView(APIView):
def get(self, request, format=None):
booksqueryset = Book.objects.all()
serializer = BookSerializer(booksqueryset, many=True)
return Response(data=serializer.data)
Read this DRF ModelSerializer Official Doc for more details

DRF detail Not found

I am working on a project that returns some metrics from a text.
The user is to enter the text in a textbox and the results are displayed to the user.
My serializers.py
from rest_framework.serializers import ModelSerializer
from .models import Entryt
class CreateEntrySerializer(ModelSerializer):
class Meta:
model = Entryt
fields = ('text',)
class EntryDetailSerializer(ModelSerializer):
class Meta:
model = Entryt
fields = ('sentence_count', 'flesch_ease', 'flesch_grade', 'smog', 'linsear', 'text_standard')
lookup_field = 'pk'
views.py
from rest_framework.generics import CreateAPIView, RetrieveAPIView
from .serializers import EntryDetailSerializer, CreateEntrySerializer, Entryt
class CreateEntryView(CreateAPIView):
model = Entryt
serializer_class = CreateEntrySerializer
queryset = Entryt.objects.all()
class ResultView(RetrieveAPIView):
serializer_class = EntryDetailSerializer
queryset = Entryt.objects.all()
urls.py
from django.conf.urls import url
from .views import ResultView, CreateEntryView
urlpatterns = [
url(r'^', CreateEntryView.as_view(), name='create'),
url(r'^result/(?P<pk>[0-9]+)/$', ResultView.as_view(), name='result'),
]
http://localhost:8000/flesch/result/2/ url like this show's nothing though there is an item with that id in the db.
How do I go about fixing this and any tips on making the code better would be great.

Categories

Resources