我正在将一个相当复杂的自制表单转换为 Django 中的 ModelForm
。由于此表单已在生产中使用了一年多,我正在尝试尽可能多地消除陷阱并为用户提供额外的功能。
我有三个模型:Transaction
、Commission
和 Unit_type
。 Transaction
是我使用的中心模型,它有一个 Unit_type
。 Commission
派生自 Unit_type
的 base_type
。
BASE_CHOICES = (
('R', 'rent'),
('S', 'sale'),
)
class Unit_type(models.Model):
unit_name = models.CharField(max_length=250)
base_type = models.CharField(max_length=1, choices=BASE_CHOICES)
class Commission(models.Model):
commission_name = models.CharField(max_length=250)
base_type = models.CharField(max_length=1, choices=BASE_CHOICES)
class Transaction(models.Models):
unit_type = models.ForeignKey(Unit_type)
commission = models.ForeignKey(Commission, blank=True, null=True)
当我显示我的表单时,我只能显示与 Unit_type
具有相同 base_type 的 Commission
,方法是:
class TransactionForm(forms.ModelForm):
class Meta:
model = Transaction
def __init__(self, unit_type, *args, **kwargs):
super(TransactionForm, self).__init__(*args, **kwargs)
self.fields['commission'].queryset = Commission_type.objects.filter(base_type=unit_type.base_type)
在我看来,我总是将表单创建为 TransactionForm(instance=transaction, unit_type=unit_type)
。
现在,MySQL 中的一个简单查询让我了解到一些 Commission
的使用或多或少取决于所选的 Unit
:
SELECT `unit_type_id`, `commission_id`, COUNT(*)
FROM `app_transaction`
GROUP BY `unit_type_id`, `commission_id`
结果:
+----------------+-----------------+------------+
| unit_type_id | commission_id | COUNT(*) |
+----------------+-----------------+------------+
| 1 | 1 | 367 |
| 1 | 3 | 2 |
| 1 | 4 | 26 |
| 2 | 1 | 810 |
| 2 | 3 | 54 |
| 2 | 4 | 865 |
| 3 | 6 | 2065 |
| 3 | 7 | 16 |
| 3 | 8 | 79 |
+----------------+-----------------+------------+
现在我想根据上述计数在 self.fields['commission']
中订购我的查询集。我已经尝试在 __init__()
中使用 values()
:
def __init__(self, unit, *args, **kwargs):
super(TransactionForm, self).__init__(*args, **kwargs)
transactions = Transaction.objects.filter(unit_type=unit)
transactions = transactions.values('commission').annotate(Count('commission)).order_by('-commission')
但现在我陷入了如何在我的查询集中保持这个顺序的问题。有没有一种简单的方法可以基于此 ValuesQuerySet
执行新的查询集?还是我完全看错了?
最佳答案
您只需要为 Count 使用一个 kwarg 并在 order_by
中使用相同的 kwarg
transactions = transactions.annotate(commission_count=Count('commission)).order_by('-commission_count')
https://docs.djangoproject.com/en/1.5/topics/db/aggregation/#cheat-sheet
关于django - 基于计数的 ModelForm 订单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18352662/