Issue
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.
Solution
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. E.g. 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!
Answered By - Rick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.