1

I have models like this:

class Model1(models.Model):
    time = models.DateTimeField(auto_now=True)

class Model2(models.Model):

    model1= models.ForeignKey(Model1, on_delete=models.CASCADE, related_name="my_list")
    f1 = models.FloatField()

I want to create endpoint for send data like this:

{"time":"123", "my_list":[{"f1":"123"}, {"f1":"123"}, {"f1":"123"}]}

This is my serializer

class TestSerializer(serializers.ModelSerializer):


 class Meta:
        model = Model1
        fields = ('id',
                  'time',
                  'my_list',)

How i can send json like i want? (

{"time":"123", "my_list":[{"f1":"123"}, {"f1":"123"}, {"f1":"123"}]}

)

1 Answer 1

3

Use ListField along with DictField as child

class TestSerializer(serializers.ModelSerializer):
    my_list = serializers.ListField(child=serializers.DictField())
    class Meta:
        model = Model1
        fields = ('id', 'time', 'my_list',)
Sign up to request clarification or add additional context in comments.

1 Comment

Depending on how complex the objects in your list are, you may want to set child=serializers.JSONField .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.