Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

195
Views
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.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!