简体   繁体   中英

making hash of data in django rest framework serializers

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM