user20709463
user20709463

Reputation:

Get email of the current logged in user in Django and filter with it to get specific statistics

When a doctor is logged in with his email and password, his dashboard shows him some statistics: the number of his patients, the number of his appointments (including past and future appointments)

I need to filter by the doctor's email (to get the appointments/patients of that specific doctor), but I couldn't get a result of any of the three filters. I tried with request.user.id and request.user.username I didn't get anything.

Here's my code : views.py:

def Home(request):
    if not request.user.is_active:
        return redirect('loginpage')
    g = request.user.groups.all()[0].name
    if g=='Patient':
        return render(request, 'homepagePatient.html')
    elif g=='Doctor':
        nbrAp=Appointment.objects.all().filter(emailDoctor=request.user).count()
        nbrPastAp = Appointment.objects.all().filter(emailDoctor=request.user, dateAp__lt=timezone.now()).order_by('-dateAp').count()
        nbrFutAp = Appointment.objects.all().filter(emailDoctor=request.user, dateAp__gte=timezone.now()).order_by('dateAp').count()
        mydict={
        'nbrAp':nbrAp,
        'nbrPastAp':nbrPastAp,
        'nbrFutAp':nbrFutAp,
        }
        return render(request, 'homepageDoctor.html', context=mydict)

models.py:

class Appointment(models.Model):
    nameDoctor= models.CharField(max_length=50)
    namePatient= models.CharField(max_length=50)
    emailDoctor = models.CharField(max_length=60)
    emailPatient = models.CharField(max_length=60)
    dateAp = models.DateField()
    timeAp = models.TimeField()
    status = models.BooleanField()
    def __str__(self):
        return self.namePatient + " will have an appointment with Dr. "+self.nameDoctor



class Doctor(models.Model):
    name= models.CharField(max_length=50)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=16)
    def __str__(self):
        return self.name

class Patient(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(unique=True)
    password = models.CharField(max_length=16)
    def __str__(self):
        return self.name

Thank you for your help !

Upvotes: 0

Views: 329

Answers (3)

Razenstein
Razenstein

Reputation: 3717

First step I recommend to do data normalization to reduce redundant information in the database - so make doctor and patient a foreign key:

class Appointment(models.Model):
    doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE)
    patient = models.ForeignKey(Patient, on_delete=models.CASCADE)
    dateAp = models.DateField()
    timeAp = models.TimeField()
    status = models.BooleanField()
    def __str__(self):
        return str(self.patient) + " will have an appointment with Dr. "+ str(self.doctor)

Second think about who is using the app. Most certainly you need the following:

  • doctors and other staff are the users and need to login with password
  • patients are only persons in the database that do not login as they are not using the app

If so, then doctors should be represented by the django User model like:

from django.contrib.auth.models import User

class Appointment(models.Model):
    doctor = models.ForeignKey(User, on_delete=models.CASCADE)
    ...

or better as the User model of your app is defined in settins.py:

from django.conf import settings

class Appointment(models.Model):
    doctor = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    ...

the query would then look like:

... Appointment.objects.all().filter(doctor=request.user) ...

As patients are not users they can just be a model with some fields like name, adress etc.:

class Patient(models.Model):
    name = models.CharField(max_length=50)
    email = models.EmailField(unique=True)
    street = ...
    city = ....
    mobile = ...
    ....
    def __str__(self):
        return self.name

If the patients should also be users with a login like to have the possibility to key in their personal data at a patients terminal, then the story is different; then patients also need to be Users and you would differentiate the roles in the User Profile or Group

If you want to dive into more advanced topics like adding more fields to User or creating a UserProfile seperately ... there is a lot more to read about django way: https://docs.djangoproject.com/en/4.2/topics/auth/customizing/#extending-the-existing-user-model

Upvotes: 0

Shine
Shine

Reputation: 588

The biggest encumbrance is your model design. Rather than creating entirely new user models for a specific Domain, try re-using the Django User model.

Also, I heavily recommend studying database normalization. As there's a lot of duplicate data in your example.

E.g.

from django.db import models
from django.contrib.auth.models import User


class Appointment(models.Model):
    doctor = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )
    patient = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
    )

    dateAp = models.DateField()
    timeAp = models.TimeField()
    status = models.BooleanField()
    def __str__(self):
        return self.namePatient + " will have an appointment with Dr. " + self.nameDoctor

After which you can query the different user's directly in your code.

doctor_appointments = Appointment.objects.filter(doctor=request.user)

Upvotes: 1

Артем Котов
Артем Котов

Reputation: 99

I think the problem is that you try to filter email field by id or username. Try to filter by user.email

In my opinion its better to expand default django User model, and add flag if this user patient or doctor. Then you can just check this flag and filter another related instances.

Upvotes: 0

Related Questions