'Django tables2 TypeError: Object of type Client is not JSON serializable
I'm trying to implement a big data on django-tables2, but with bootstrap table fitches (sort, filter, export, click to select, etc). Found a solution but it works with only simple fields, in my project, some fields in the model are linked to another model:
class Cars(models.Model):
dealer = models.ForeignKey(Dealer, blank=True, null=True, on_delete=models.CASCADE)
slug = models.SlugField(null=True, unique=True)
VIN = models.CharField(max_length=19, blank=True, null=True)
model = models.CharField(max_length=50) # Car_model, on_delete=models.CASCADE
client = models.ForeignKey(Client, blank=True, null=True, on_delete=models.CASCADE)
manager = models.ForeignKey(Manager, blank=True, null=True, on_delete=models.CASCADE)
This is my code in views.py:
class TableViewMixin(SingleTableMixin):
# disable pagination to retrieve all data
table_pagination = False
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
# build list of columns and convert it to an
# ordered dict to retain ordering of columns
# the dict maps from column name to its header (verbose name)
table: Table = self.get_table()
table_columns: List[Column] = [
column
for column in table.columns
]
# retain ordering of columns
columns_tuples = [(column.name, column.header) for column in table_columns]
columns: OrderedDict[str, str] = OrderedDict(columns_tuples)
context['columns'] = columns
return context
def get(self, request, *args, **kwargs):
# trigger filtering to update the resulting queryset
# needed in case of additional filtering being done
response = super().get(self, request, *args, **kwargs)
if 'json' in request.GET:
table: Table = self.get_table()
data = [
{column.name: cell for column, cell in row.items()}
for row in table.paginated_rows
]
return JsonResponse(data, safe=False)
else:
return response
class CarsTableViewMixin(TableViewMixin, ListView):
template_name = 'modules/cars_tables3.html'
table_class = CarsTable
queryset = Cars.objects.all()
I have an error: TypeError: Object of type Client is not JSON serializable "GET /table3/?json&searchText= HTTP/1.1" 500 146887
I know that there is something to add in serialising my json string, but I'm not yet good at it. Have you some suggestions on it please?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
