2017-05-28 84 views
0

我有一個一對多的關係模型如下:Django的filterset - 一對多查詢

class Client(models.Model): 
    name = models.CharField.... 
    ... 

class Contract(models.Model): 
    client = models.ForeignKey(Client) 
    type = models.IntegerField() 
    start_date = models.DateField(null=True, blank=True) 
    ... 

我想構建一個高效的查詢集返回其最新(即一個與最近開始的所有客戶端日期)contract.type等於5

我怕我掙扎周圍試圖解決這一個。

任何人都可以幫忙嗎?

如果它不是可能的,那麼我正在考慮加入到客戶端的字段是一對一的關係,以最新的合同,這每一個合同的修改時間保持。然後,我可以簡單地使用該字段進行搜索。

最終我去下面的,如果這個可以進行優化,那麼請讓我知道 - TA。

# this function is called by django-filter 
    # its purpose is to remove any clients where the contract with the most recent start date 
    # does not have a type that matches the value parameter 
    def filter_contract_type(self, queryset, name, value): 
     # for each client get the contract with the latest start date 
     # if that contract has a type that matches the value parameter, then hold on to the pk of its parent 
     # finally strip out any clients that are not in this list, from the queryset django-filter passed in and then return it 
     client_ids = [] 
     value = int(value) 
     for client in queryset: 
      con = Contract.objects.filter(client=client).order_by('start_date').last() 
      if con is not None and con.type == value: 
       client_ids.append(con.client.id) 

     return queryset.filter(pk__in=client_ids) 
+1

'父= models.ForeignKey(家長)'你的意思是'父= models.ForeignKey(客戶端)'? –

+0

什麼是你的數據庫後端,postgres有什麼機會? – schwobaseggl

+0

葉先生,對不起Ayush,我做了必要的編輯。 ta – SteveMcG

回答

0

對不起因爲我沒有得到你的更好的方法,但你可以嘗試:

# Get ez list 
Cs = Contract.objects.filter(type = 5).order_by(start_date) 
# and run the loop to get the 5 dif cl id 
cl_ids= [] 
num = 0 
for c in Cs: 
    if c.client_id not in cl_ids: 
     cl_ids.append(c.client_id) 
     if len(cl_ids) > 4: 
      break 
+0

很感謝Nam – SteveMcG