Home > Mobile >  Cannot query "amclient15": Must be "Client" instance
Cannot query "amclient15": Must be "Client" instance

Time:12-08

Am trying to filter the appointments made by a specific client when he is logged in

def user( request):
    
    client = request.user.client
    request.user.id
    
    appointments = Appointment.objects.filter(user=request.user)

    context = { 'client': client, 'appointments':appointments
               }

    return render(request, 'users/user.html', context)

Here are my models. i can be able to display all the appointments but the problem comes in when i try to filter specific appointments for users to view on their own pages

# Create your models here.


from django.db import models
from django.contrib.auth.models import User
from django.utils.translation import gettext_lazy as _



class Client(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    profile_pic = models.ImageField(default="profile1.png", null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.name



class Worker(models.Model):
    CATEGORY = (
        ('Plumbing', 'Plumbing'),
        ('Electrical', 'Electrical'),
        ('Cleaning', 'Cleaning'),
    )
 
    user = models.OneToOneField(
        User, null=True, blank=True, on_delete=models.CASCADE)
    name = models.CharField(max_length=200, null=True)
    phone = models.CharField(max_length=200, null=True)
    email = models.CharField(max_length=200, null=True)
    profile_pic = models.ImageField(
        default="profile2.png", null=True, blank=True)
    area_of_operation = models.CharField(max_length=200, null=True)
    category = models.CharField(max_length=200, null=True, choices=CATEGORY)
    description = models.CharField(max_length=200, null=True, blank=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    date_updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name


class Appointment(models.Model):
    CATEGORY = (
        ('Plumbing', 'Plumbing'),
        ('Electrical', 'Electrical'),
        ('Cleaning', 'Cleaning'),
    )
    STATUS = (
        ('Pending', 'Pending'),
        ('Delivered', 'Delivered'),
    )

    user = models.ForeignKey(Client, null=True, on_delete=models.SET_NULL)
    name = models.CharField(max_length=200, null=True)
    worker = models.ForeignKey(Worker, null=True, on_delete=models.SET_NULL)
    category = models.CharField(max_length=200, null=True, choices=CATEGORY)
    task_date = models.DateField(_("Task Date"), blank=True, null=True)
    task_location = models.CharField(max_length=200, null=True)
    date_created = models.DateTimeField(auto_now_add=True, null=True)
    status = models.CharField(max_length=200, null=True, choices=STATUS)
    budget = models.FloatField(null=True)
    task_description = models.CharField(max_length=1000, null=True, )
    task_image = models.ImageField(
        null=True, blank=True, help_text='Optional.')

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



RATING=(
    (1,'1'),
    (2,'2'),
    (3,'3'),
    (4,'4'),
    (5,'5'),
)



class YoReview(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    worker = models.ForeignKey(Worker, on_delete=models.CASCADE)
    review_text = models.TextField()
    review_rating = models.CharField(choices=RATING, max_length=150)

    def get_review_rating(self):
        return self.review_rating

This is the error message that i received when i ran the project

December 08, 2021 - 13:02:36
Django version 3.2.9, using settings 'it.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Internal Server Error: /user/
Traceback (most recent call last):
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:\Users\PROBOOK 440\projects\it\david\decorators.py", line 24, in wrapper_func
    return view_func(request, *args, **kwargs)
  File "C:\Users\PROBOOK 440\projects\it\david\views.py", line 216, in user
    appointments = Appointment.objects.filter(user=request.user)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\query.py", line 941, in filter
    return self._filter_or_exclude(False, args, kwargs)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\query.py", line 961, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, args, kwargs)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\query.py", line 968, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\sql\query.py", line 1393, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\sql\query.py", line 1412, in _add_q
    child_clause, needed_inner = self.build_filter(
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\sql\query.py", line 1320, in build_filter
    self.check_related_objects(join_info.final_field, value, join_info.opts)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\sql\query.py", line 1147, in check_related_objects
    self.check_query_object_type(value, opts, field)
  File "C:\Users\PROBOOK 440\Envs\myenv\lib\site-packages\django\db\models\sql\query.py", line 1128, in check_query_object_type
    raise ValueError(
ValueError: Cannot query "amclient15": Must be "Client" instance.

CodePudding user response:

The Appointment.user field is not an instance of User, its a instance of Client but request.user is still a User.

You want to follow the relation from Client and filter on Client.user field.

i.e

appointments = Appointment.objects.filter(user__user=request.user)

Its always a good idea to name your fields for what it is, i.e the ForeignKey in Appointment should probably be named client instead to remind you that it is in fact not a user but a client.

  • Related