想法是Requisition
可以有多行,这就是为什么我在unique_together
和parent_req
上加入了sequence
约束的原因。
每行都有一个与之关联的状态。我为每个状态添加了1到5的评分,但可能会有某些状态的评分相同。我的想法是,我想保存所有行中评分最高的状态,并将其传递给模板。我尝试使用.annotate
来获得最高评分,但是我无法获取与该评分相关的实际状态字段。如果某个评分存在多个状态,那么它应该抢先看到它。
示例:
**Status** | **Rating**
status1 | 1
status2 | 2
status3 | 3
status4 | 3
status5 | 4
status6 | 5
models.py
class Requisition(models.Model):
username = models.ForeignKey(
'users.CustomUser',
on_delete=models.CASCADE,
related_name='req_user')
signature = models.CharField(
max_length=10,
blank=True,
null=True)
class RequisitionLine(models.Model):
parent_req = models.ForeignKey(
'Requisition',
on_delete=models.CASCADE,
related_name='par_req_line')
sequence = models.PositiveIntegerField()
status = models.ForeignKey(
'RequisitionStatus',
related_name='req_status',
on_delete=models.CASCADE,
blank=True,
null=True)
class Meta:
unique_together = ('parent_req','sequence')
class RequisitionStatus(models.Model):
status = models.CharField(
max_length=20)
rating = models.SmallIntegerField()
def __str__(self):
return self.status
views.py
def pending_action(request):
requisition_status = [
'All', 'Created', 'For Assistance', 'Assistance Complete', 'Assistance Rejected',
]
FA_status = RequisitionStatus.objects.get(status='For Assistance')
current_status = 'All'
status_list = []
all_status = RequisitionStatus.objects.all()
status_list = [status.status for status in all_status]
if request.GET.get('Filter') in status_list:
user_req_lines_incomplete = RequisitionLine.objects.filter(
Q(parent_req__username=request.user)
& Q(status__status=request.GET.get('Filter')))
current_status = request.GET.get('Filter')
else:
user_req_lines_incomplete = RequisitionLine.objects.filter(
parent_req__username=request.user) \
.exclude(status__status='Completed')
# This is where I query for the status and right now im grabbing the actual rating.
# I want to be able to access the status like I am accessing the aggregated price
user_reqs = Requisition.objects.filter(
par_req_line__in=user_req_lines_incomplete) \
.annotate(
aggregated_price=Sum('par_req_line__total_price'),
header_status=Max('par_req_line__status__rating'))
return render(
request,
'req/pending_action.html',
{
'user_reqs': user_reqs,
'user_req_lines_incomplete': user_req_lines_incomplete,
'requisition_status': requisition_status,
'current_status': current_status,
'FA_status': FA_status,
})