我正在將一個相當複雜的自制表單轉換爲Django中的ModelForm
。由於這種形式在生產中使用了一年多,我試圖儘可能多地去除陷阱並給予用戶額外的功能。基於計數的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)
當我顯示我的狀態,我可以通過只顯示Commission
S的具有相同base_type爲Unit_type
:
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
s的使用或多或少取決於所選的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
的新查詢集?或者我看到這完全錯誤?
你可以試試django的聚合或註解方法 – drabo2005
@ abda2005我已經在我的__init __()中使用了一個註解,現在我需要一種方法將這些結果放到我的字段的查詢集中,像'self.fields [ 'commission']。queryset = Commission.objects.filter(pk__in = transactions)' –