DJANGO ListView returns HTTPResponse, but I need a json - json

I am having a problem around the Class Based Views in Django. I need to create JSON responses, instead of rendering to a template.
class AllItem(ListView):
model = MyModel
context_object_name = 'items'
template_name = 'mymodel/index.html'
I also have a serializer class
class SpendingConfigSerializer(serializers.ModelSerialier):
class Meta:
model = SpendingConfig
fields = ('record_date', 'amount', 'name')
Does anyone know how to connect them?
Thanks
Z.

You can make use of a ListAPIView and specify your SpendingConfigSerializer as serializer:
from rest_framework import generics
class UserList(generics.ListCreateAPIView):
queryset = SpendingConfig.objects.all()
serializer_class = SpendingConfigSerializer

Related

Access Json object name

I want to get data with request.data.columns in frontend.I can do it with ViewSet with list method but how to do it with generics.APIView.
Below is my viewsets and generics code:
class TestList(viewsets.ViewSet):
queryset = Test.objects.all()
def list(self,request):
serializer = TestSerializer(self.queryset, many = True)
return Response({'columns': serializer.data})
class TestList(generics.RetriveAPIView):
queryset = Test.objects.all()
serializer_class = TestSerializer
class TestList(APIView):
queryset = Test.objects.all()
def list(self,request):
serializer = TestSerializer(self.queryset, many = True)
return Response({'columns': serializer.data})
change your urls.py like this.
path(r"url", TestList.as_view({"get": "list"}))
Correct code:
class TestList(APIView):
queryset = Test.objects.all()
def list(self,request):
queryset = self.get_queryset()
serializer = TestSerializer(queryset, many = True)
return Response({'columns': serializer.data})
Details about why i had to add queryset = self.get_queryset() instead of directly access self.queryset.From official drf documentation:
queryset - The queryset that should be used for returning objects from this view. Typically, you must either set this attribute, or override the get_queryset() method. If you are overriding a view method, it is important that you call get_queryset() instead of accessing this property directly, as queryset will get evaluated once, and those results will be cached for all subsequent requests.

How to make QuerySet JSON serializable?

I have a problem with creating a new object in my Rest Framework.
As much I as understand, when I tried to overwrite item's field so it could have all the items that are in my database. I thought, that this would work, and it showed me the working page and I could choose an item. But when I tried to post it to create a new object, it said "Object of type 'Item' is not JSON serializable"
I was trying to figure it out, how to convert Item.objects.all() into JSON data. But nothing helped me. I understand, that this isn't really hard to do, but I can't figure it out on my own.
So I ask for your help, how to solve this problem?
Here's my serializer
from rest_framework import serializers
from items.models import OrderItem, Item
class OrderItemSerializer(serializers.ModelSerializer):
item = serializers.ChoiceField(choices=Item.objects.all())
class Meta:
model = OrderItem
fields = ('item', 'size', 'quantity', 'id')
from rest_framework import serializers
from items.models import OrderItem, Item
class OrderItemSerializer(serializers.ModelSerializer):
item = serializers.SerializerMethodField()
class Meta:
model = OrderItem
fields = ('item', 'size', 'quantity', 'id')
def get_item (self, obj):
# in value list name all fields u want or empty for defaults
return Item.objects.all().values_list('pk', flat=True)
...
and inside the create method (post in Serializer)
...
def create(self, validated_data):
req = self.context.get('request')
items = req.data.get('item')
if items:
[OrderItem.item.add(
oneitem) for oneitem in items]

Incomplete json structure - no count/next/previous/results field

like many times before, im trying to send data from my Django backend to my Ionic mobile app.
This time, however, for some reason, the .jsons im parsing are coming out incomplete.
A complete .json:
{"count":1,"next":null,"previous":null,"results":[{"codigo":"qwe","area":"ewq","especies":[],"id":1}]}
My incomplete .json:
[{"nome_ficheiro":"1520529086252.jpg","id":26,"especie":"Ameijoa Branca","zona":"L6","data":"09/06/2018"}]
IONIC is struggling with identifying what I'm parsing as a .json, which makes sense since there is no "results" field.
Here are the relevant snippets of my django code:
Views.py (both Views are doing the same thing! This is just me trying out different approaches!)
class resultUploadViewSet(viewsets.ViewSet):
def list(self, request, nome_ficheiro):
queryset = labelResult.objects.all()
nome = nome_ficheiro
answer = queryset.filter(nome_ficheiro=nome)
serializer = resultSerializer(answer, many=True)
return Response(serializer.data)
class resultUploadView(APIView):
serializer_class = resultSerializer
def get(self, request, nome_ficheiro):
queryset = labelResult.objects.all()
nome = nome_ficheiro
answer = queryset.filter(nome_ficheiro=nome)
serializer = self.serializer_class(answer, many=True)
return Response(serializer.data)
Models.py
class labelResult(models.Model):
nome_ficheiro = models.CharField(max_length=120)
especie = models.CharField(max_length=120)
zona = models.CharField(max_length=120)
data = models.CharField(max_length=120)
Urls.py
urlpatterns = [
url(r'results/(?P<nome_ficheiro>.+)/$', resultUploadViewSet.as_view({'get': 'list'})),
url(r'results1/(?P<nome_ficheiro>.+)/$', resultUploadView.as_view())]
Serializers.py
class resultSerializer(serializers.ModelSerializer):
class Meta:
model = labelResult
fields = ('nome_ficheiro','id','especie','zona', 'data')
Any idea why my .jsons are coming out incomplete?
you should use ListAPIView so the pagination is applied.
http://www.django-rest-framework.org/api-guide/generic-views/#listapiview
more on pagination you can find here:
http://www.django-rest-framework.org/api-guide/pagination/

Django DRF TypeError: object is not iterable, how to approach this?

Wondering what I'm doing wrong here. I'm running DRF with a React frontend. Trying to get one serializer to GET and POST a user's selected stations.
The AJAX POST works great, but the get on a page's initial load no longer works, and Django tells me: TypeError: 'Station' object is not iterable.
From reading around I'm vaguely aware that I shouldn't be declaring station with many = True, as this is causing the exception to be thrown. But I can't find any other way to get it working, it mangles the JSON POST request if I remove this option and stops the data validating.
The create is using custom code and is working fine.
Should I be trying to get this to work seamlessly or should I just hack it/make a different serializer to do the POST? Am I doing this in a logical way or have I got it all back-to-front?
models.py
class Station(models.Model):
network = models.ForeignKey(Network, on_delete=models.CASCADE)
name = models.CharField(db_column='name', max_length=256) # Field name made lowercase.
latitude = models.FloatField()
longitude = models.FloatField()
users = models.ManyToManyField('Account', through='UserStations')
class Meta:
managed = True
def __str__(self):
return self.name
class UserStations(models.Model):
station = models.ForeignKey(Station, on_delete=models.CASCADE)
user = models.ForeignKey(Account, on_delete=models.CASCADE)
serializers.py
class UserStationListSerializer(serializers.ModelSerializer):
class Meta:
model = Station
# fields = ('id', 'name')
fields = '__all__'
class UserStationsSerializer(serializers.ModelSerializer):
def __init__(self, *args, **kwargs):
#many = kwargs.pop('many', True)
print args
super(UserStationsSerializer, self).__init__(*args, **kwargs)
station = UserStationListSerializer(many=True, required = False, read_only=False)
views.py
class UserStationList(generics.ListCreateAPIView):
queryset = UserStations.objects.all()
serializer_class = UserStationsSerializer
Urls.py
from django.conf.urls import url
from . import views
from .views import StationList, AccountViewSet
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken.views import obtain_auth_token
router = DefaultRouter()
router.register(r'users', AccountViewSet)
urlpatterns = router.urls
urlpatterns += [
url(r'^$', views.StationList.as_view(), name='station-list'),
url(r'user-station-list/', views.UserStationList.as_view(), name='user-station-list'),
url(r'^obtain-auth-token/$', obtain_auth_token),
url(r'station-list/', views.StationList.as_view(), name='user-station-list'),
]

Django - serializing queryset along with related models

There are hundreds of posts related to an elementary goal.
I have a simple model:
class ModelA(models.Model):
# I've got only two fields in reality,
# but let's suppose there are 150 of them
class ModelB(models.Model):
# fields
class ModelC(models.Model):
field_c = Integer
modelA = models.ForeignKey('ModelB')
modelB = models.ForeignKey(ModelC)
model_c_instance = ModelC.objects.select_related().get(pk=pk)
All I want to do is to come up with a JSON object which would include the fields for ModelA and ModelB.
Wadofstaff (post) does not suit for Django 1.7 and higher.
This post does not shed light on how I should serialize the objects.
This post tell about Full Serializers, but there's no code snippet to see how it is used.
My final JSON object should look like
[{
"model": "userinfo",
"fields": {
"field_c ": "9966",
"modelA": [{
# modelA fields
}
etc...
}]
Do I need REST framework ? Or Full Serializers ?
Please could anyone suggest a structured answer to this topic. I can't come up with a solution for two weeks.
You want to use a nested relationship. You don't show anything about the userinfo model so this answer doesn't take that into account. You could do something similar to this pseudo-code:
# serializers.py
from rest_framework import serializers
class ModelASerializer(serializers.ModelSerializer):
class Meta:
model = ModelA
class ModelBSerializer(serializers.ModelSerializer):
class Meta:
model = ModelB
class ModelCSerializer(serializers.ModelSerializer):
modelA = ModelASerializer(many=True)
modelB = ModelBSerializer(many=True)
class Meta:
model = ModelC