3

So I'm working on a website that uses Django and having trouble with the serializer. Here is the code:

class DataPointSerializer(serializers.ModelSerializer):
    value = serializers.DecimalField(max_digits=30, decimal_places=15)
    sensor = serializers.ChoiceField(choices=list(Sensor.objects.all()))
    point = serializers.ChoiceField(choices=list(MapPoint.objects.all()))

    class Meta:
        model = DataPoint
        fields = "__all__"

    def create(self, attrs, instance=None):
        return DataPoint(value=attrs['value'], sensor=attrs['sensor'], point=attrs['point'])

My DataPoint model uses value as a decimal field, sensor as a foreign key, and point as another foreign key. I'm using the choice fields to fetch the objects that have been created but from the create function, I get a TypeError saying that (Sensor object) is not JSON serializable. I assume the same is happening for point but I am unsure of what to do. Any help would be appreciated!

Aneesh R S
  • 3,807
  • 4
  • 23
  • 35
Timothyw0
  • 31
  • 1
  • 3

2 Answers2

0

According to choices is A list of valid values, or a list of (key, display_name) tuples. Specify field from Sensor and MapPoint objects or tuple (field, display_name):

list(Sensor.objects.values_list('id').all())

or, for example (if your model has name field)

list(Sensor.objects.values_list('id', 'name').all())
Amit Rahav
  • 115
  • 1
  • 15
miksyn
  • 93
  • 7
0

The main problem here is you are passing DataPoint class as the result of create function instead of DataPoint object. That is what the error means. And also sensor and point are primary keys. So you can use PrimaryKeyRelatedField in the serializer.

Try this

class DataPointSerializer(serializers.ModelSerializer):
    value = serializers.DecimalField(max_digits=30, decimal_places=15)
    sensor = serializers.PrimaryKeyRelatedField(queryset=Sensor.objects.all())
    point = serializers.PrimaryKeyRelatedField(queryset=MapPoint.objects.all())

    class Meta:
        model = DataPoint
        fields = "__all__"

    def create(self, validated_data, instance=None):
        return DataPoint.objects.create(**validated_data)

Note : Since you are using model serializer, you don't need to specify fields or write definition for create or update functions. Model serializer itself finds the fields from the model and it should contains definitions for simple create and update functions. You can see the details here. Considfering these, your DataPointSerializer can be minimized to

class DataPointSerializer(serializers.ModelSerializer):
    class Meta:
        model = DataPoint
        fields = "__all__"
Aneesh R S
  • 3,807
  • 4
  • 23
  • 35