Home > Mobile >  How to stop the Post request, if there is already the same data is in the Model
How to stop the Post request, if there is already the same data is in the Model

Time:09-28

I am trying to stop the instance if the data matches in the DB. But i tried and failed again and again.

My Code:

models.py

class Doctor(models.Model):
    """
    Manages data of consulting doctors working in the Hospital
    """

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    address = models.CharField(max_length=40)
    contact = models.IntegerField()
    department = models.CharField(max_length=50)
    active = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.user} ({self.department})"


class Patient(models.Model):
    """
    Manages data of patient
    """

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    address = models.CharField(max_length=40)
    contact = models.IntegerField()
    symptoms = models.CharField(max_length=50)
    active = models.BooleanField(default=False)

    def __str__(self):
        return f"{self.user} ({self.symptoms})"


    class Appointment(models.Model):
        """
        Manages the appointment details
        """
    
        patient_name = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='doctor')
        doctor_name = models.ForeignKey(Doctor, on_delete=models.CASCADE, related_name='patient')
        appointment_date = models.DateTimeField()
        active = models.BooleanField(default=False)
    
        def __str__(self):
            return str(self.patient_name)   " has appointment with "   str(self.doctor_name)

serializers.py

from rest_framework import serializers
from api.models import Patient, Doctor, Appointment


class AppointmentSerializer(serializers.ModelSerializer):
    """
    Appointment serializer class
    """

    class Meta:
        model = Appointment
        fields = "__all__"


class DoctorSerializer(serializers.ModelSerializer):
    """
    Doctor serializer class
    """
    user = serializers.StringRelatedField(read_only=True)
    patient = AppointmentSerializer(many=True, read_only=True)

    class Meta:
        model = Doctor
        fields = "__all__"


class PatientSerializer(serializers.ModelSerializer):
    """
    Patient serializer class
    """

    user = serializers.StringRelatedField(read_only=True)
    doctor = AppointmentSerializer(many=True, read_only=True)

    class Meta:
        model = Patient
        fields = "__all__"

views.py

from django.shortcuts import render
from rest_framework.exceptions import ValidationError
from rest_framework.response import Response
from rest_framework import status, viewsets
from rest_framework.views import APIView

from api.models import Doctor, Patient, Appointment
from api.serializers import DoctorSerializer, PatientSerializer, AppointmentSerializer
from rest_framework import generics
from rest_framework.decorators import action

# Create your views here.


class DoctorAPI(generics.ListAPIView):
    """
    Doctor working in hospitals list
    """

    queryset = Doctor.objects.all()
    serializer_class = DoctorSerializer


class PatientAPI(generics.ListAPIView):
    """
    Patient visiting in hospital list
    """

    queryset = Patient.objects.all()
    serializer_class = PatientSerializer

class DoctorDetailAPI(generics.ListAPIView):
    serializer_class = DoctorSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        return Doctor.objects.filter(patient=pk)


class PatientDetailAPI(generics.ListAPIView):
    serializer_class = PatientSerializer

    def get_queryset(self):
        pk = self.kwargs['pk']
        return Patient.objects.filter(doctor=pk)


class AppointmentDetailAPI(APIView):
    def get(self, request):
        appointment = Appointment.objects.all()
        serializer = AppointmentSerializer(appointment, many=True)
        return Response(serializer.data)

    def post(self, request):
        serializer = AppointmentSerializer(data=request.data)
        patient_name = Patient.objects.all()
        doctor_name = Doctor.objects.all()
        # print(serializer)
        if serializer.is_valid():
            appoint_data = Appointment.objects.filter(patient_name=patient_name)
            print(appoint_data)


class AppointmentCreateAPI(generics.RetrieveUpdateDestroyAPIView):
    queryset = Appointment.objects.all()
    serializer_class = AppointmentSerializer

My task:

  1. --> TO Resitrict the user to make appointment if there is already an appoinment is schedule to the Doctor.

CodePudding user response:

You have to override post method in LISTAPIVIEW and get data which you are going to filter before saving. For example;

class DoctorAPI(generics.ListAPIView):

queryset = Doctor.objects.all()
serializer_class = DoctorSerializer

def post(self,request,*args,**kwargs):
     data=request.data.get("the name of input")
     instance = Doctor.objects.filter(the field name which you are going 
     to compare).exist()
     if instance:
     return Response({"error":"This data is in database"})


     

CodePudding user response:

You can also add a validation in the serializer to check if an existing appointment already exists like this:

class AppointmentSerializer(serializers.ModelSerializer):
    ...
    def validate(self, attrs):
        if not self.instance: # I'm creating an appointment
            if Appointment.objects.filter(
                doctor_name=attrs['doctor_name'], 
                appointment_date=attrs['appointment_date'], 
                active=True, 
            ).exists():
                raise serializers.ValidationError(
                    f'Appointment already exists for {attrs['doctor_name']}'
                )
  • Related