Melly
Melly

Reputation: 745

How do I merge data of two objects in Django REST Framework

So let's say I have this 2 models

Poll:

class Poll(models.Model):

    title = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_available = models.BooleanField(default=True)
    date_created = models.DateTimeField(auto_now_add=True)

    def __str__(self):

        return self.title

Options:

class Option(models.Model):

    title = models.CharField(max_length=255)
    poll = models.ForeignKey(Poll, on_delete=models.CASCADE)

    def __str__(self):

        return f'{self.poll.title} - {self.title}'

These two objects are connected with ForeignKey. Now let's say I have a frontend that renders both options and the question (title of the poll) but I only want make a single API call to the backend. Basically I need the API to looked like this:

{
    "title": "Which is the best frontend framework?",
    "options":[
                {
                    "id": 1,
                    "title": "React"
                },
                {
                    "id": 2,
                    "title": "Vue"
                },
                {
                    "id": 3,
                    "title": "Angular"
                }
            ]
}

How what method/technique should I use to merge two objects like this?

Upvotes: 0

Views: 584

Answers (1)

Reza Heydari
Reza Heydari

Reputation: 1211

Based on DRF docs

class OptionSerializer(serializers.ModelSerializer):
    class Meta:
        model = Option
        fields = ['id', 'title']
class PollSerializer(serializers.ModelSerializer):
    options = OptionSerializer(source='option_set', many=True)
    class Meta:
        model = Poll
        fields = ['title', 'options']

Upvotes: 2

Related Questions