colletjb colletjb - 1 year ago 58
JSON Question

Django - Rest Framework Multiple models

I'm starting to use Django Rest Framework, it's a great tool!

I'm actually stuck in something easy, but no way to figure out how to do... I have two models, CustomUser and Order. Here, a CustomUser has 0 to many Orders.

I would like to generate a JSON HTTPResponse with the following format:

"user": {
"city": "XXX",
"firstName": "XXX",
"zip": "XXX",
"taxNumber": "XXX",
"lastName": "XXX",
"street": "XXX",
"country": "XXX",
"email": "XXX"},
"orders": [{
"id": "XXX",
"plan": "XXX",
"date": "XXX",
"price": "XXX"

I already have my user in session (request) and I fetch the required Orders with the following line:

# 2. Load user's orders
orders = Order.objects.filter(user=request.user)

I've created two serializers "OrderSerializer(serializers.ModelSerializer)" and "CustomUserSerializer(serializers.ModelSerializer)", but I've no clue how to merge both into the expected result.

Thanks a lot for your help.

Best regards

Answer Source

The question is old, so it may have been answered, but something like this should work:

class OrderSerializer(serializers.ModelSerializer)
    class Meta:
        model = Order

class UserSerializer(serializers.ModelSerializer)
    orders = OrderSerializer(many = True)
    class Meta:
        model = user
        fields = ('city', 'firstName', 'zip', 'taxNumber', 'lastName', 'street', 'country', 'email', 'orders')