sFishman
sFishman

Reputation: 133

Does a Django Application that uses REST framework need a model?

I built an application that uses REST apis to inject information into a huge already existing database for a company. The application is a web form that the user fills out. My application then serializes the user's responses into a json that it uses to send post requests to the existent db.

My Django app also is connected to a SQL Server db where it is saving the responses of the user into the fields that I created in my models.py.

Is there a better way to do this? It seems like I'm saving all the information twice! A waste of space.

Upvotes: 0

Views: 94

Answers (1)

Jaap Joris Vens
Jaap Joris Vens

Reputation: 3560

I don't think you need anything in your models.py for this particular application. Personally I like the approach of letting the Form handle the saving process. You could do something like this:

import json
from django import forms

class MyForm(forms.Form):
    field1 = forms.CharField()
    field2 = forms.IntegerField()
    ...

    def save(self):
        json_data = json.dumps(self.cleaned_data)
        # insert code here to send the data to your REST API

Your view can then simply call the form.save() method in your view, even though this form is not a ModelForm.

if request.POST:
    form = MyForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect(success_url)
return render(request, 'form.html', {'form': form})

Upvotes: 1

Related Questions