How to make QuerySet JSON serializable? - json

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]

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.

DJANGO ListView returns HTTPResponse, but I need a 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

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 rest framework - request context key error

I have two models (Like and News). I am using django-rest-framework to make a web api out of it.
class Like(models.Model):
user = models.ForeignKey(User)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey('content_type', 'object_id')
class News(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=150)
...
likes = GenericRelation(Like)
A Like object has its own user field to store who liked the News object. Now to check if a specific user exists in any of the likes of a News object, I am getting request.user from a SerializerMethodField.
class NewsSerializer(serializers.HyperlinkedModelSerializer):
user = UserSerializer()
likes_count = serializers.IntegerField(source='likes.count', read_only=True)
user_in_likes = serializers.SerializerMethodField()
class Meta:
model = News
fields = ('user', 'title', 'body', 'article_image', 'pub_date', 'likes_count', 'user_in_likes')
def get_user_in_likes(self, obj):
user = self.context['request'].user
what = obj.likes.filter(user=user).exists()
return what
When I go the /news/ url, I get the json objects including the user_in_likes to true/false for each news object.
However, I have another serialzer for different model which imports NewsSerializer class and other similar serializers:
class ActivityObjectRelatedField(serializers.RelatedField):
def to_representation(self, value):
if isinstance(value, User):
serializer = UserSerializer(value)
elif isinstance(value, Job):
serializer = JobSerializer(value)
elif isinstance(value, News):
serializer = NewsSerializer(value)
elif isinstance(value, Tender):
serializer = TenderSerializer(value)
else:
raise Exception('Unexpected type of tagged object')
return serializer.data
class ActivitySerializer(serializers.HyperlinkedModelSerializer):
actor = ActivityObjectRelatedField(read_only=True)
target = ActivityObjectRelatedField(read_only=True)
class Meta:
model = Activity
fields = ('url', 'actor', 'verb', 'target', 'pub_date')
Now if I visit /activities/, to get the activities objects I am getting an error:
KeyError at /activities/
'request'
And it points to the line of SerializerMethod of NewsSerialize class where self.context['request'].user is used.
Exception Location: /vagrant/myproject/news/serializers.py in get_user_in_likes, line 25
Again if I visit /news/ url, everything is fine and I get news objects. What am I missing here? Why is request not being recognized in the ActivitiesSerializer class? Please help me solve this problem. Thank you.
You are getting this error because you are not passing request in the context when instantiating the NewsSerializer class or other similar serializers in the to_representation() method.
You are manually instantiating the particular serializer class in to_representation() method. So, after instantiation, that particular serializer does not have access to ActivitySerializer's context thereby leading to the error.
You can pass the ActivitySerializer's context during instantiation of the relevant serializer in the to_representation() method.
class ActivityObjectRelatedField(serializers.RelatedField):
def to_representation(self, value):
if isinstance(value, User):
serializer = UserSerializer(value, context=self.context) # pass context
elif isinstance(value, Job):
serializer = JobSerializer(value, context=self.context) # pass context
elif isinstance(value, News):
serializer = NewsSerializer(value, context=self.context) # pass context
elif isinstance(value, Tender):
serializer = TenderSerializer(value, context=self.context) # pass context
else:
raise Exception('Unexpected type of tagged object')
return serializer.data
It seems like you don't populate the context dictionary of NewsSerializer with your request in the /activities/ view.
You probably use a class based view provided by Django REST Framework which populates this dictionary for you (see the get_serializer_context() method) and passes it to the Serializer instance. That's why it's automatically available to your serializer in your /news/ view.
In your /activities/ view, though, the context is passed to ActivitySerializer and isn't (automatically) propagated further from there. That's why there's no request key in your context dictionary of NewsSerializer. You would need to pass your request object to the NewsSerializer instance. To pass extra context to a Serializer you can add a context parameter containing a dictionary when instantiating (see the DRF documentation).