I have a customer model and an event model. event model refer to the customer. A customer has many events. My requirement is when I get the customer, I need the latest event object of the customer. When I call the customer Get API, it shows the following error,
TypeError at /api/v1/customer
is not JSON serializable
My Models
class Customer(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=20, unique=True)
#some more fields to go
def __str__(self):
return str(self.name)
def latest_event_name(self):
"""Return latest event """
latest_event = self.customer_events.order_by('-event_date').last()
return latest_event if latest_event else None
class Event(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
event_name = models.CharField(max_length=200, unique=True)
customer = models.ForeignKey(customer_models.Customer, db_index=True, on_delete=models.SET_NULL,
related_name='customer_events', null=True)
#some more fields to go
serializer
class CustomerSerializer(serializers.ModelSerializer):
latest_event_name = serializers.ReadOnlyField()
class Meta:
model = Customer
fields = '__all__'
Event- clearly one of them is preventing serialization.CustomerEventinstance, what is it supposed to serialize into?latest_event_namethat isn't serializable since DRF has no idea how to serialize the queryset resultlatest_event_name = EventSerializer(read_only=True)do what you're looking for? (You'll need to write the event serializer)code return latest_event.event_name if latest_event else Nonein model,` 'latest_event_name = serializers.ReadOnlyField()' ` will work in serializer. It will return the event name. But I need the full event object.