Last active
April 28, 2018 10:54
-
-
Save BuildWithLal/d8afd693d510fa3ff756249651cc79e4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class SessionHistoryCreateSerializer(DocumentSerializer): | |
class Meta: | |
model = SessionHistory | |
fields = '__all__' | |
# check date... | |
def validate(self, data): | |
data = super().validate(data) | |
if data['start_date'] >= data['end_date']: | |
raise ValidationError('start date must be behind end data') | |
# check data usage.... | |
def validate_voucher_data_limit(self): | |
data = self.validated_data | |
voucher = data['voucher'] | |
user_sessions = SessionHistory.objects.filter(user=data['user'], voucher=voucher) | |
data_usage = 0 | |
for session in user_sessions: | |
data_usage = data_usage + session['data_usage'] | |
if data_usage >= voucher.data_limit: | |
raise ValidationError('voucher data limit expired.') | |
View.py | |
class SessionHistoryCreate(generics.CreateAPIView): | |
#model = models.SessionHistory | |
serializer_class = serializers.SessionHistoryCreateSerializer | |
def create(self, request, *args, **kwargs): | |
serializer = self.get_serializer(data=request.data) | |
serializer.is_valid(raise_exception=True) | |
serializer.validate_voucher_data_limit() | |
self.perform_create(serializer) | |
current_user = User.objects.get(username=serializer.validated_data.get('username')) | |
response = {**current_user} | |
return Response(response, status=status.HTTP_200_OK) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment