Stack Exchange
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.


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.

I got this error message, "Generic detail view TitleDetail must be called with either an object pk or a slug"

@JasonTK Sorry, I just missed one line in the sample, please add slug_url_kwarg = "emp_no" as well. Answer updated.

Awesome. I used the get_object() and it works too, but I'm using your code, so much easier. Thanks so much.

Good, then maybe you could accept this answer and mark it as useful, so others could get benefits as well :)

Is that by clicking on the checkmark to turn green? sorry as you can see i'm new to stackoverflow,

You can override the get_object() method to do whatever you want:
def get_object(self, queryset=None):
    queryset = self.get_queryset() if queryset is None else queryset
    return get_object_or_404(queryset, emp_no_id=self.kwargs['emp_no'])

In case you haven't seen it before, see the get_object_or_404() documentation.
