如何使用 DetailView 中 PK(主键)字段以外的不同字段进行查询

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()

数据库中的示例数据:

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  

为什么它给我

PAGE NOT FOUND: No title found matching the query.

你可以覆盖 get_object() 方法来做任何你想做的事:

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'])

如果您以前没有看过,请参阅 get_object_or_404() documentation

事实上,您不必重写 get_object 方法,您需要做的只是像这样定义一个合适的 slug 字段(不是 pk_url_kwarg):

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

here 是源代码,如果你想看看后面发生了什么。