我有一个查询,我可以在shell中运行,并根据我的模型和关系的工作方式得到正确的答案:
# And let's see each business's employees:
employees=Employee.objects.filter(business_locations__business=business).distinct()
这很有效,我可以将其设置为员工并让所有为企业工作的员工。麻烦的是,在尝试实际使用此模型并从中呈现列表视图时,我不确定这是一个干净的方法。如果您看到list.html代码(最后一个代码段),您可以看到我尝试在列表中提供为企业工作的员工数量,然后理想情况下提供使用<-- --> arrow widget thingy编辑员工的链接。
我知道我必须在下面的视图中这样做,但我不确定最干净的方式。最好的我可以想出一个for循环和一个id的地图?
我有一个view方法:在我的views.py中:
def business_list(request):
object_list = Business.objects.all()
paginator = Paginator(object_list, 25) # 3 posts in each page
page = request.GET.get('page')
#make a map into the object list some how so I can have this data at the end...
try:
business = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer deliver the first page
business = paginator.page(1)
except EmptyPage:
# If page is out of range deliver last page of results
business = paginator.page(paginator.num_pages)
return render(request, 'ipaswdb/group/list.html', {'page':page, 'business':business, 'object_list':object_list})
然后我对该视图的渲染视图模板就是这个list.html:
{% extends "ipaswdb/base.html" %}
{% block title %}Businesses{% endblock %}
{% block content %}
<h1>Businesses</h1> <p> Search: </p>
{% with object_list.count as total_businesses %}
<h2>
There are {{ total_businesses }} businesses
</h2>
{% endwith %}
<table class="table">
<tr>
<th> ID</th>
<th> Business Name</th>
<th> Comments</th>
<th> Total employees</th>
<th>Edit</th>
<th>Term</th>
{% for group in groups %}
<tr>
<td><a href="{{ business.id }}">{{ business.id }}</a></td>
<td><a href="{{ business.id }}">{{ business.business_name }}</a></td>
<td> {{ business.notes|truncatewords:30|linebreaks }}</td>
<!-- How do i do this? -->
<td><a href="linktoaddremoveemployeestoabusiness"> {{ business.business_total }}</a></td>
<td> editbutton</td>
<td>termbutton</td>
</tr>
{% endfor %}
</table>
{% include "pagination.html" with page=groups %}
{% endblock %}
型号:
class Employee(models.Model):
first_name = models.CharField(max_length = 50)
business_locations = models.ManyToManyField('BusinessLocations', through='EmployeeLocations')
class EmployeeLocations(models.Model):
employee = models.ForeignKey('Employee', on_delete=models.CASCADE)
business_location = models.ForeignKey('BusinessLocations', on_delete=models.CASCADE)
created_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now=True)
def __str__(self):
return self.provider.first_name
class BusinessLocations(models.Model):
address = models.ForeignKey('Address', on_delete= models.SET_NULL, null=True)
business = models.ForeignKey('Business', on_delete=models.CASCADE)
doing_business_as = models.CharField(max_length = 255)
created_at=models.DateField(auto_now_add=True)
updated_at=models.DateField(auto_now=True)
def __str__(self):
return self.doing_business_as
class Business(models.Model):
business_name = models.CharField(max_length=50)
我从这个stackoverflow问题中得到了这些帮助: Giving a model knowledge of a many-to-many related model in django