Search code examples
pythondjangosqlitelistviewdetailview

How to query using a different field other than the PK (primary key) field in DetailView


url.py

urlpatterns = [
    url(r'^employee/(?P<emp_no>[0-9]+)/$', TitleDetail.as_view(), name='e-title'),  
    # /employee/10001/
    ]

views.py

class TitleDetail(DetailView):
    model = Title
    pk_url_kwarg = "emp_no"

    def get_context_data(self, **kwargs):
        context = super(TitleDetail, self).get_context_data(**kwargs)
        context['title_list'] = Title.objects.filter(emp_no_id=self.kwargs['emp_no'])
        return context

models.py

class Title(models.Model):
    emp_no = models.ForeignKey(Employee)
    title = models.CharField(max_length=50)
    from_date = models.DateField()
    to_date = models.DateField()

sample data in database:

id          title            from_date   to_date     emp_no_id 
----------  ---------------  ----------  ----------  ----------
1           Senior Engineer  1986-06-26  9999-01-01  10001     
2           Staff            1996-08-03  9999-01-01  10002  

why does it give me

PAGE NOT FOUND: No title found matching the query.


Solution

  • In fact, you don't have to override get_object method, what you need to do is just to define a proper slug field(not pk_url_kwarg) like this:

    class TitleDetail(DetailView):
        model = Title
        slug_field = "emp_no"
        slug_url_kwarg = "emp_no"
    

    And here is the source code if you'd like to see what has happened behind.