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
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With