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

谁都会走 提交于 2020-01-17 06:45:02

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/43728982/how-to-query-using-a-different-field-other-than-the-pk-primary-key-field-in-de

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!