Save value in one field depending on the value of another field in Rest Framework

0

Good morning

I am trying to change what I have done in forms to serializers and I find that with forms, depending on a date that is entered, it calculates another date for another field.

I have seen that the SerializedMethodField does what I need but it does not work to save data, what other options do I have?

FechaValidoHasta = serializers.SerializerMethodField()

    def get_FechaValidoHasta(self, obj):
        seisMeses = relativedelta(months=6)
        return obj.FechaValidoDesde+seisMeses 

It seems like it could be using Custom Fields, but I do not see how to reference the other field when calculating the date.

Thanks!

    
asked by Cecilio Alonso 18.12.2017 в 09:39
source

1 answer

0

After researching it, I do not see clearly that Rest Framework has implemented this in the part related to the serializers. If I am wrong and if it includes it, please provide a new answer. To fix it in another way, what I have done is overwrite the methods perform_update and perform_create in the ModelViewSet, in the file views.py, taking the value of the other field from self.resquest.POST ['ValidDate') and thus be able to calculate the Value of Date ValueUp. In the file serializers.py, this case, it is not necessary to indicate anything special.

#views.py

class CertificadoBackendListAPI(viewsets.ModelViewSet):
    queryset = Certificado.objects.all()
    serializer_class = CertificadoEditSerializer

    def perform_create(self, serializer):
        seisMeses = relativedelta(months=6)
        Fecha=datetime.strptime(self.request.POST['FechaValidoDesde'],'%Y-%m-%d')+seisMeses 
        serializer.save(FechaValidoHasta=datetime.date(Fecha))

    def perform_update(self, serializer):
        seisMeses = relativedelta(months=6)
        Fecha=datetime.strptime(self.request.POST['FechaValidoDesde'],'%Y-%m-%d')+seisMeses 
        serializer.save(FechaValidoHasta=datetime.date(Fecha))
    
answered by 19.12.2017 / 12:36
source