'Object of type <> is not JSON serializable Django REST Framework
I am trying to create a search function inside my class-based view using Django Rest Framework, but it does not seems to work.
when I try to search for some customers it gives me an error:
raise TypeError(f'Object of type {o.class.name} '
TypeError: Object of type Customer is not JSON serializable
I know there is some question out there looking like mine, but I dont think any of them can help my. I am a bit new to Django REST framework.
my view:
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]
return Response({'customers': customers})
the Customer model:
class Customer(models.Model):
user = models.OneToOneField(User, primary_key=True, on_delete=models.PROTECT)
rank = models.ForeignKey(Rank, default=2, on_delete=models.PROTECT)
personal_id = models.IntegerField(db_index=True)
phone = models.CharField(max_length=35, db_index=True)
@property
def full_name(self) -> str:
return f'{self.user.first_name} {self.user.last_name}'
@property
def accounts(self) -> QuerySet:
return Account.objects.filter(user=self.user)
@property
def can_make_loan(self) -> bool:
return self.rank.value >= settings.CUSTOMER_RANK_LOAN
@property
def default_account(self) -> Account:
return Account.objects.filter(user=self.user).first()
def make_loan(self, amount, name):
assert self.can_make_loan, 'User rank does not allow for making loans.'
assert amount >= 0, 'Negative amount not allowed for loan.'
loan = Account.objects.create(user=self.user, name=f'Loan: {name}')
Ledger.transfer(
amount,
loan,
f'Loan paid out to account {self.default_account}',
self.default_account,
f'Credit from loan {loan.pk}: {loan.name}',
is_loan=True
)
the customer serializer:
class CustomerSerializer (serializers.ModelSerializer):
class Meta:
fields = ('user', 'rank', 'personal_id', 'phone', 'full_name', 'accounts', 'can_make_loan', 'default_account')
model = Customer
Solution 1:[1]
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})
Solution 2:[2]
@TrueGopnik answer is right. but i don't think you need to write queryset for search filter. you can use django restframework serachfilters. which make your work less. please go thorugh this documentation https://www.django-rest-framework.org/api-guide/filtering/#searchfilter
Solution 3:[3]
You must edit you view class like this
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]
return customers
Just return customers not a dictionary
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | TrueGopnik |
Solution 2 | Meet |
Solution 3 | Mohammad Ali |