Home > Net >  Django Rest Framework: TypeError: Object of type Facility is not JSON serializable
Django Rest Framework: TypeError: Object of type Facility is not JSON serializable

Time:10-28

When i try to send a put request to my LeadUpdate Api Endpoint i receive the following error:

Django Rest Framework: TypeError: Object of type Facility is not JSON serializable

Can someone tell me why that is? This serializer is basically supposed to save assigned facilities within a lead when a lead gets updated and create a "LeadFacilityAssociation" object if any facility id's end up being sent with the IntegerField.

serializer.py

class LeadUpdateSerializer(serializers.ModelSerializer):
    is_owner = serializers.SerializerMethodField()
    assigned_facilities = serializers.IntegerField(required=False)
    scheduled_datetime = serializers.DateTimeField(required=False)

    class Meta:
        model = Lead
        fields = (
            "id",
            "assigned_facilities",
            "scheduled_datetime",
            "is_owner",
        )
        read_only_fields = ("id", "is_owner")

    def get_is_owner(self, obj):
        user = self.context["request"].user
        return obj.agent == user

    def create(self, validated_data):
        assigned_facilities = validated_data.pop("assigned_facilities")
        scheduled_datetime = validated_data.pop("scheduled_datetime")
        instance = Lead.objects.create(**validated_data)
        instance.LeadFacilityAssociation.create(assigned_facilities=assigned_facilities,scheduled_datetime=scheduled_datetime)
        return instance
        
    def to_representation(self, instance):
        representation = super().to_representation(instance)

        representation["scheduled_datetime"] = instance.LeadFacilityAssociation.first().scheduled_datetime
        representation["assigned_facilities"] = instance.LeadFacilityAssociation.first().assigned_facilities
        print(instance.LeadFacilityAssociation.first().assigned_facilities)
        return representation

models.py

class Facility(models.Model):

    name = models.CharField(max_length=150, null=True, blank=False)
  
    def __str__(self):
        return self.Name


class Lead(models.Model):
    first_name = models.CharField(max_length=40, null=True, blank=True)
    last_name = models.CharField(max_length=40, null=True, blank=True)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"


class LeadFacilityAssociation(models.Model):
    assigned_facilities = models.ForeignKey(Facility,  related_name='LeadFacilityAssociation')
    lead = models.ForeignKey(Lead,  related_name='LeadFacilityAssociation')
    scheduled_datetime = models.DateTimeField(null=True, blank=True)

views.py

class LeadUpdateView(UpdateAPIView):
    permission_classes = [IsAuthenticated, IsLeadOwner]
    serializer_class = LeadUpdateSerializer

    def get_queryset(self):
        return Lead.objects.all()

CodePudding user response:

The issue is in the to_representation method for the serializer.

def to_representation(self, instance):
        representation = super().to_representation(instance)

        representation["scheduled_datetime"] = instance.LeadFacilityAssociation.first().scheduled_datetime
        representation["assigned_facilities"] = instance.LeadFacilityAssociation.first().assigned_facilities
        print(instance.LeadFacilityAssociation.first().assigned_facilities)
        return representation

The issue is that in this part representation["assigned_facilities"] = instance.LeadFacilityAssociation.first().assigned_facilities an instance of the assigned facility is returned and as the error message says instances are not JSON serializable. What you can do is assign representation["assigned_facilities"] to the assigned facilities name or id like this:

def to_representation(self, instance):
        representation = super().to_representation(instance)

        representation["scheduled_datetime"] = instance.LeadFacilityAssociation.first().scheduled_datetime
        # You can use the name or whatever field fits similar to what you have above
        representation["assigned_facilities"] = instance.LeadFacilityAssociation.first().assigned_facilities.id
        print(instance.LeadFacilityAssociation.first().assigned_facilities)
        return representation
  • Related