Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

197
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda