Arun SS
Arun SS

Reputation: 1911

django rest framework : <Objectname: Objectname object> is not JSON serializable

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__'

Upvotes: 0

Views: 386

Answers (2)

Arun SS
Arun SS

Reputation: 1911

Anyway now fixed the issue by the following method.

def latest_event(self):
latest_event = self.customer_events.order_by('-event_date').last()
eventDict = None
if latest_event:
    eventDict = {"event_id": latest_event.id, "event_name": latest_event.event_name}
return eventDict

Not sure whether its the correct method or not.

Upvotes: 0

PROW
PROW

Reputation: 182

As you are using Events in

def latest_event_name(self): ...

you'll have to create a serializer for the Event model, because that method returns an instance of the model Event.

I think that, if you just return the id of the Event as a str, you will not have that problem, so you wouldn't have to create a seralizer for the Event model.

Upvotes: 2

Related Questions