Anna Jeanine
Anna Jeanine

Reputation: 4125

QuerySet working in shell but not in Views.py - Django 1.10

When executing the following QuerySet in the Django shell (python manage.py shell):

Employee.objects.filter(restaurant__pk = 1)

I get a result back:

<QuerySet [<Employee: Joyce McDonnals>]>

Please excuse me, because I am new to Django. I am trying to implement this queryset dynamically in my webpage through the PK. The get_queryset which I have defined in the views.py is:

class EmployeeList(ListView):
    template_name= "Restaurants/employee_list.html"
    model = Employee
def get_queryset(self, **kwargs):
        queryset = Employee.objects.filter(pk= restaurant.pk)
        return queryset

But this returns the error:

NameError at /restaurant/1/employees/
name 'restaurant' is not defined
Request Method: GET
Request URL:    http://127.0.0.1:8001/restaurant/1/employees/
Django Version: 1.10.5
Exception Type: NameError
Exception Value:    
name 'restaurant' is not defined

I have tried some variants for the queryset in my views.py, but I can't seem to get it to work. Could someone help me to define this queryset?

Upvotes: 1

Views: 365

Answers (3)

Daniel Roseman
Daniel Roseman

Reputation: 599796

The problem is not the queryset, but standard Python scoping. You need to think about where the value for restaurant is supposed to be coming from.

In your case, it is clearly coming from the URL; assuming you have a URL something like this:

url(r'^restaurant/(?P<restaurant_id>\d+)/employees/$', ...)

named capturing group, that value will be stored in self.kwargs['restaurant_id']. So you should use that in the filter.

Note also that you can use restaurant_id directly as the field, rather than doing a JOIN

So:

queryset = Employee.objects.filter(restaurant_id=self.kwargs['restaurant'])

Upvotes: 2

Mangesh
Mangesh

Reputation: 1031

try this -

queryset = Employee.objects.filter(restaurant__pk=pk_value)

you should pass pk_value here and restaurant field should be foreign key to other table. You can check by passing pk_value = 1 as you are doing in shell.

hope this helps. for more info check django model docs - https://docs.djangoproject.com/en/1.10/topics/db/models/

Upvotes: 0

Alexander Tyapkov
Alexander Tyapkov

Reputation: 5047

You are not providing restaurant into the get_queryset. Probably it should be like that:

   def get_queryset(self):
        self.restaurant = get_object_or_404(Restaurant, name=self.args[0])
        return Emploee.objects.filter(pk=self.restaurant)

Upvotes: 0

Related Questions