Django object is not JSON serializable
simplejson
and json
don't work with django objects well.
Django's built-in serializers can only serialize querysets filled with django objects:
data = serializers.serialize('json', self.get_queryset())
return HttpResponse(data, content_type="application/json")
In your case, self.get_queryset()
contains a mix of django objects and dicts inside.
One option is to get rid of model instances in the self.get_queryset()
and replace them with dicts using model_to_dict
:
from django.forms.models import model_to_dict
data = self.get_queryset()
for item in data:
item['product'] = model_to_dict(item['product'])
return HttpResponse(json.simplejson.dumps(data), mimetype="application/json")
Object of type '' is not JSON serializable in DRF
You need to return serializer.data
instead of serializer.validated_data
.
Have a look at the updated code for ReservationViewSet
:
class ReservationViewSet(CreateModelMixin, GenericViewSet):
serializer_class = ReservationSerializer
queryset = Reservation.objects.all()
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response(status=status.HTTP_201_CREATED, data=serializer.data)
the data
property is meant to translate the model instance into the Python native dictionary type. Python Dictionary can be serialized as a JSON Response.
Object of type is not JSON serializable Django REST Framework
As i wrote in comment under your question, you should serialize queryset
class staff_search_partial(generics.ListAPIView):
renderer_classes = [JSONRenderer, TemplateHTMLRenderer]
template_name = 'BankApp/staff_search_partial.html'
serializer_class = CustomerSerializer
permissions_classes = [permissions.IsAuthenticated, ]
def post(self, request):
assert request.user.is_staff, 'Customer user routing staff view.'
search_term = request.POST['search_term']
print(type(search_term))
customers = Customer.objects.filter(
Q(user__username__contains=search_term) |
Q(user__firstname__contains=search_term) |
Q(user__lastname__contains=search_term) |
Q(user__email__contains=search_term) |
Q(personalid__contains=search_term) |
Q(phone_contains=search_term)
)[:15]
customers_data = CustomerSerializer(customers, many=True).data
return Response({'customers': customers_data})
Getting Error Object of type bytes is not JSON serializable in django
The reason for your error is that JSON doesn't understand 'bytes'. So you'd need to convert the bytestring to string.
The following is one way of doing it.
def s(reqeust):
car_report= connection.cursor()
car_report.execute('''select....''')
car_report_data = car_report.fetchall()
json_res=[]
for row in car_report_data:
srow = [x.decode('utf-8') if isinstance(x, bytes) else x for x in row]
json_obj = dict(number=srow[0],
name=srow[1],
total_trips=srow[2],
status=srow[3],
day1_trips=srow[4],
day2_trips=srow[5],
day3_trips=srow[6],
day4_trips=srow[7],
day5_trips=srow[8],
day6_trips=srow[9],
day7_trips=srow[10])
json_res.append(json_obj)
print(json_res,'json_res')
return JsonResponse(json_res,safe=False)
Related Topics
How to Look Ahead One Element (Peek) in a Python Generator
Access Memory Address in Python
How to Get Rid of Beautifulsoup User Warning
How to Use Win32 API with Python
What Is Different Between All These Opencv Python Interfaces
Installing Multiple Versions of a Package with Pip
How to Bind the Enter Key to a Function in Tkinter
Converting "Yield From" Statement to Python 2.7 Code
How to Match Any String from a List of Strings in Regular Expressions in Python
How to Apply Itertools.Product to Elements of a List of Lists
List' Object Has No Attribute 'Get_Attribute' While Iterating Through Webelements
Python: How to Send Mail with To, Cc and Bcc
Why Does Python's _Import_ Require Fromlist
How to Change Effective Process Name in Python
How to Get 'Real-Time' Information Back from a Subprocess.Popen in Python (2.5)