简体   繁体   中英

Building a django detailview and listview without using <int:pk>

I'm building a django app that displays a database of employees and their salaries. It uses a postgres database. I'm struggling to figure out how to build a DetailView without using a primary key for the url. I think using a slug may be the solution but I'm not sure how to implement that and haven't had much luck searching online.

My Listview for the list of all companies:

class AllCompanies(FormMixin, generic.ListView):
template_name = 'AllCompanies.html'
form_class = SearchForm
model = bigdatabase
queryset = bigdatabase.objects.order_by().values('company').distinct()
context_object_name = 'companies'

Example Database snippet, bigdatabase:

Company EmployeeName Salary
Alpha   Jim          100000
Alpha   Tim          125000
Beta    Bim          90000

My list view displays all unique company names as intended. However, I'm not sure how to proceed and build a detailview to display more info on each unique company. I'd like to show things like number of employees, median salary, etc.

I've done something similar by building a detailview for employees, but that relied upon using their primary key in the url since each employee is unique. Since I have many entries for many companies in my database, how would I build a detailview and accompanying url structure to support that?

Any advice or pointers as to move this along would be greatly appreciated.

You can add a slugfield to your bigdatabase model. Try using the autoslugfield and set it to the company name like:

from django_extensions.db.fields import AutoSlugField

class bigdatabase(models.Model): 
company = Models.Charfield()
slug = models.AutoSlugField(populate_from=['company']
......

This makes sure you company name will automatically be translated for use in the url. Eg when you have spaces in the company name, using str:company will translate in weird characters for the space. Using in your url translates this to a -.

Naming your model field slug makes sure that your detailview get the slug field by default. See docs .

Your views will then look something like:

class CompanyDetailView(DetailView):
model = bigdatabase 
template_name = '#path_to_template'
slug_url_kwarg = 'slug' # I believe this is done correctly by default but in case you change the field name. 

In your url you can do something like mentioned above:

path('company/<slug>', views.CompanyDetailView.as_view())

Happy coding!

Not sure that I understood correctly, but I thought you can use something like this:

path('company/<str:name>', views.company_detail_view)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM