Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 262
colletjb Avatar asked Oct 31 '13 14:10

colletjb


People also ask

What is the difference between ModelSerializer and HyperlinkedModelSerializer?

The HyperlinkedModelSerializer class is similar to the ModelSerializer class except that it uses hyperlinks to represent relationships, rather than primary keys. By default the serializer will include a url field instead of a primary key field.

What is Serializers in Django REST framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

What is Django REST framework good for?

Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.


1 Answers

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

like image 198
user1260486 Avatar answered Oct 06 '22 16:10

user1260486