Home > Mobile >  making hash of data in django rest framework serializers
making hash of data in django rest framework serializers

Time:12-31

i want to making a SHA256 hash of some fields in my serializer and set it to another field in the same serializer, this is my model:

class Something(models.Model):

x = models.CharField(max_length=300)
y = models.IntegerField()
z = models.IntegerField()
f = models.IntegerField()
hash = models.CharField(max_length=300)

first user defines x,y,z and f. after that i need to generate hash automaticly like this hash = x y z f

my serializer :

class SomethingSerializers(serializers.ModelSerializer):
    class Meta:
        model = Something
        fields = ['x', 'y', 'z', 'f', 'hash']

what is the best decision?

CodePudding user response:

You can add a model property calculating your hash:

class Something(models.Model):
    x = models.CharField(max_length=300)
    y = models.IntegerField()
    z = models.IntegerField()
    f = models.IntegerField()

    @property
    def hash(self):
        return your_hashed_value

CodePudding user response:

You can add a SerializerMethodField which hashes those values:

class SomethingSerializers(serializers.ModelSerializer):
    hash = serializers.SerializerMethodField()

    class Meta:
        model = Something
        fields = ['x', 'y', 'z', 'f', 'hash']

    def get_hash(self, obj):
        return obj.x   obj.y   obj.z   obj.f  # or your custom logic

Note that this won't save the hash in the db

CodePudding user response:

Just override save method of model like this:

import hashlib

class Something(models.Model):
    x = models.CharField(max_length=300)
    y = models.IntegerField()
    z = models.IntegerField()
    f = models.IntegerField()
    hash = models.CharField(max_length=300)
      
    def save(self, *args, **kwargs):
         input = self.x   str(self.y)   str(self.z)   str(self.f)
         result = hashlib.sha256(input.encode())
         self.hash = result.hexdigest()
         super(Something, self).save(*args, **kwargs)

And serializers are fine.

  • Related