How can I override get method in django Model?

限于喜欢 提交于 2020-01-01 05:34:27

问题


I want to do encode the data before saving it to a database table and decode it after reading it from the database table. I wanted to override django get and save methods.

something like:

class UserData(models.Model):
    userid = models.IntegerFields
    data = models.charField(max_length=25)

    def save(self, *args, **kwargs):
        encode_data(self.data)
        super(UserData, self).save(*args, **kwargs)

    def get(self, *args, **kwargs):
        data = super(UserData, self).get(*args, **kwargs)
        return decode_data(data)

django models have save method and I am able to override it and do what i want. But, they doesnt seem to have a get method which I can override. How can I achieve this? I want the data to be decoded on calling UserData.objects.all() or UserData.objects.get() or UserData.objects.filter() or any other such methods available


回答1:


Usually, you do this by overriding __init__. But since __init__ on Django Models does all kind of funky business, it's not recommended to override it. Instead, listen for the post_init signal and do your decoding there:

def my_decoder(instance, **kwargs):
    instance.decoded_stuff = decode_this(instance.encoded.stuff)

models.signals.post_init.connect(my_decoder, UserData)



回答2:


Try reading docs about writing custom manager. Remember, you are not calling get on Model, but on Model.objects, which is a some kind of Manager. Here are the docs: https://docs.djangoproject.com/en/dev/topics/db/managers/



来源:https://stackoverflow.com/questions/2492653/how-can-i-override-get-method-in-django-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!