I'm writing an application with django-tastypie and following are my models.py and resource.py files.
Models.py:
import uuid
from django.db import models
class User(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
name = models.CharField(max_length=50, null=False)
email = models.EmailField(max_length=254, null=False)
password = models.CharField(max_length=100, null=False)
role = models.CharField(max_length=16, default='basic', null=False)
def __unicode__(self):
return self.name, self.email
Resources.py:
from tastypie.resources import ModelResource
from tastypie.authorization import Authorization
from api.models import User
class UserResource(ModelResource):
class Meta:
queryset = User.objects.all()
resource_name = 'user'
authorization = Authorization()
excludes = ['password']
#allowed_methods = ['get']
Now the thing is that whenever I hit an API end point from postman, the user is created directly. Now what I don't understand is that whether the request data goes into resources and then into database or directly into the database? Actually, the thing is that I need to apply some changes to the data before it is stored in the database, like hashing the password and then storing the object in the database. I'm new to django, so how can I achieve that? Like in Flask, we can do something like:
@user.route('/users', methods=['POST'])
def create_user(user_id):
data = request.get_json(force=True)
# do all the changes we want
user = User(data)
db.session.add(user)
db.session.commit()
Now if any request comes at '/users' endpoint, we can get it's data in the 'data' variable and then whatever changes we want before storing in the database. But how to do that in django with tastypie.
Any help would be appreciated
If you have to massage data before entering into database
then Tastypie
has the notion of hydrate
and dehydrate
methods.
Check that. Here is reference hydrate and dehydrate