Skip to content
Advertisement

Django Traverse Foreign Keys

I have 3 models and I am trying to create a dashboard with a list of Trials that spans all Client Sessions for a specific client chosen via a filter.

Here are the models:

class Trial(models.Model):
    behavior_name = models.ForeignKey(Behavior, on_delete=models.CASCADE)
    client_session = models.ForeignKey(Client_Session, on_delete=models.CASCADE)
    frequency_input = models.PositiveIntegerField(default=0, blank=True)
    duration_input = models.DurationField(blank=True, default=timedelta(minutes=0))


    class Meta:
        verbose_name_plural = 'trials'

    def __str__(self):
        return str(self.id)


class Client_Session(models.Model):
    name = models.CharField(max_length=200, null=False)
    session_date = models.DateField(blank=False,null=False)
    client = models.ForeignKey(Client, on_delete=models.CASCADE)
    behaviors = models.ManyToManyField(Behavior, null=False)
    therapist = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

    class Meta:
        verbose_name_plural = 'clientsessions'

    def __str__(self):
        return self.name



class Client(models.Model):
    #user = models.ForeignKey(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=200)
    last_name = models.CharField(max_length=200)
    date_of_birth = models.DateField(blank=True, null=True)
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES,blank=True)
    gaurdian_first_name = models.CharField(max_length=200, blank=True)
    gaurdian_last_name = models.CharField(max_length=200, blank=True)
    diagnosis = models.CharField(max_length=200, choices=DIAGNOSIS_CHOICES, blank=True)
    therapist = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)

    def __str__(self):
        return self.last_name

Here is the view that im trying to create

def dashboard(request):
    # filter list of client sessions by selected client
    client_sessions = Client_Session.objects.filter(therapist=request.user)
    client = DashboardClientFilter(request.GET, queryset=client_sessions)
    client_sessions = client.qs

    #Create list of Trials across Client Sessions for the filtered client
        trial_list = Trial.objects.filter(client_session__client=client)

Advertisement

Answer

You have an error filter query you used Filter data. Expected is queryset.

Change, trial_list = Trial.objects.filter(client_session__client=client) into

client_sessions = client.qs
client_pks = client.qs.values_list('client_id',flat=True)
trial_list = Trial.objects.filter(client_session__client_id__in= list(client_pks))

trial_list = Trial.objects.filter(client_session__client__in= list(client_pks)).distinct() distinct() method is used to remove duplicated but it not work some databases

10 People found this is helpful
Advertisement