Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

django serializer method field read write

class ProjectSerializer(serializers.ModelSerializer):
    contract_price = WritableSerializerMethodField(deserializer_field=serializers.DecimalField(max_digits=12, decimal_places=2))

    def get_contract_price(self, project):
        return project.contract_price

    def set_contract_price(self, value):
        return value
Comment

django serializer method field read write

class WritableSerializerMethodField(serializers.SerializerMethodField):
    def __init__(self, **kwargs):
        self.setter_method_name = kwargs.pop('setter_method_name', None)
        self.deserializer_field = kwargs.pop('deserializer_field')

        super().__init__(**kwargs)

        self.read_only = False

    def bind(self, field_name, parent):
        retval = super().bind(field_name, parent)
        if not self.setter_method_name:
            self.setter_method_name = f'set_{field_name}'

        return retval

    def get_default(self):
        default = super().get_default()

        return {
            self.field_name: default
        }

    def to_internal_value(self, data):
        value = self.deserializer_field.to_internal_value(data)
        method = getattr(self.parent, self.setter_method_name)
        return {self.field_name: self.deserializer_field.to_internal_value(method(value))}
Comment

PREVIOUS NEXT
Code Example
Python :: Sound alerts in Jupyter for code completion and exceptions 
Python :: numpy.empty sorce code 
Python :: Python - How To Pad String With Spaces 
Python :: string contains element of list python 
Python :: InsertionSort 
Python :: print treelib.Tree 
Python :: Python, variables, Print() advanced, Input(), Variables ,INT, STR, FLOAT, BOOL, Casting 
Python :: Python OrderedDict - LRU 
Python :: load py file converted from .ui file 
Python :: django creat app return _bootstrap._gcd_import 
Python :: python sleeping with a varible 
Python :: python - dashboard 
Python :: how to make a window in python ursina 
Python :: HttpResponse Object Error in view.py 
Python :: initials of name 
Python :: pygame download for python 3.10 
Python :: adding if statements and for loop in pyhton with tuple 
Python :: Create a matrix from a range of numbers (using arange) 
Python :: expand array to a certain size python 
Python :: converting from series to dataframe with tabulate 
Python :: separate alphanumeric list 
Python :: select randomly from list in loop 
Python :: how to use displacy 
Python :: django column to have duplicate of other 
Python :: python load array 
Python :: readme python convert to pdf 
Python :: appending hdf5 files 
Python :: linear algebra ipython notebook 
Python :: discord.py assign role 
Python :: map dataframe parallel 
ADD CONTENT
Topic
Content
Source link
Name
5+6 =