How can I handle multiple separate models in a single AJAX request using Django REST Framework?

In my Django project (version 5.1.2), I need to handle data from multiple models in a single AJAX request from the front end. For example, I have a form that collects user information and shipping addresses at the same time. I want to submit this data in a single request and have it saved in separate models in the database.

I’m using Django REST Framework to manage the API, but I’m unsure how to properly validate and save multiple models at once in one request.

Currently, I am using one ViewSet per model, but I don’t know how to combine them in a single AJAX request and ensure that if there’s an error in one of the models, none of the data is saved (i.e., I want proper transaction handling).

Is there a recommended solution for this in Django 5.1.2? What is the best way to handle multiple models in a single AJAX request in Django REST Framework?

Details:

I'm using Django 5.1.2. Both user and address information need to be saved transactionally.

What I Tried:

I created two separate ViewSets for the user information and shipping address models. Then, I tried to send the form data via a single AJAX POST request from the front end. I attempted to handle the data in two different views but ran into challenges coordinating them. Specifically, I wanted to use Django REST Framework's serializers to validate the data, ensuring that if one model fails validation, neither model's data gets saved.

What I Expected:

I expected to be able to submit data from both models (user and address) in a single request, have Django validate both, and save the data to the respective models transactionally. That means if the user data is valid but the address data has an error, no data should be saved until both are valid.

What Happened:

I ran into issues with managing the transaction between the two ViewSets. Either one model's data would save before the other, or the validation errors for one model would not properly prevent the other model's data from being saved. This led to inconsistent database states where partial data was stored.

Create a custom API endpoint with a combined serializer that nests the user and address serializers.

Use a Combined Serializer. You can nest the user and address serializers within one main serializer.

Implement Transaction Management by using transaction.atomic() in your view to ensure both models save together.

Finally, ff either model fails validation, raise an error to prevent any data from being saved.

Back to Top