[Answered ]-Merge two models with one-to-one relationship into one model serializer (Django)

1👍

You’ll have to specify the fields for your related model in the serializer.

Your profile class is probably as below(most standard way):

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    age = models.PositiveIntegerField()
    country = models.CharField(max_length=50)


    def __str__(self):
        return self.user.username

The follwing serializer gives you a flat json:

class UserSerializer(serializers.ModelSerializer):
    age = serializers.IntegerField(source="profile.age")
    country = serializers.CharField(source="profile.country")

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'email',
            'age',
            'country',
        ]
👤ari

Leave a comment