10

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

2 Answers 2

18

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')

Thanks,

SS

Sign up to request clarification or add additional context in comments.

2 Comments

Still, how to use this serializer? userializer = UserSerializer( Order.objects.get(pk=1), User.objects.filter(is_active=True) ) print userializer.data. Is this going to work?
Tried such a thing in my project. But I am not aware how to write the views.py for such a response. Can you please post the answer for this?
2

Since orders are related to user, you should use Nested relationships.

2 Comments

The link is broken
It seems to have been a link to DRF v2 tomchristie.com/rest-framework-2-docs/api-guide/…

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.