2017-02-27 25 views
0
Customer.objects.filter(customer_id__in=contact_list_senders) 

contact_list_senders是重複查詢集,涉及一些CUSTOMER_IDS:django的objects.filter(x__in = y),其中y是重複查詢集

{sender_id1,sender_id2,sender_id1,sender_id2,sender_id1}

當我試圖找到從contact_list_senders QuerySet的客戶對象與上面的代碼

實際輸出:

{customer1表,顧客2}

所需的輸出

{customer1表,顧客2,customer1表,顧客2,customer1表}

我瞭解實際輸出有道理的,因爲只有2個Customer對象與這些聯繫人匹配。你能幫我取得理想的結果嗎?

models.py:

class Customer(models.Model): 
    customer_id = models.CharField(max_length=244, blank=False, null=False) 
    first_name = models.CharField(max_length=244, blank=True, null=True) 
    last_name = models.CharField(max_length=244, blank=True, null=True) 
    email = models.CharField(max_length=244, blank=False, null=False) 
    enrollment_method = models.CharField(max_length=244, blank=True, null=False) 
    account_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2) 
    reserved_balance = models.DecimalField(default=0000.00, max_digits=6, decimal_places=2) 
    modified = models.DateTimeField(auto_now_add=True) 
    created = models.DateTimeField(auto_now_add=True) 
+0

看起來你必須用list_sender做一個循環,然後將結果合併成一個。 – viviwill

回答

1

你有一個良好的開端,但你必須做休息蟒蛇:

customers = {x.customer_id: x for x in Customer.objects.filter(customer_id__in=contact_list_senders)} 
final_customer_list = [customers[x] for x in contact_list_senders] 

這首先建立一個字典映射客戶ID的客戶(沒有每個數據庫的查詢),然後使用它來構建最終列表,包括重複項。

假設您的第一個列表是客戶ID列表,但如果不是,則可以輕鬆進行修改。

+0

偉大的解決方案,無需多次查詢。非常感謝! – Berk

+0

不是問題!:) – Ben

0

我沒有看到你的表上有任何主索引,我想customer_id字段應該是1。在這種情況下,如果你有兩個型號,一個多到一的關係(很多發件人可以涉及到一個客戶)的模型看起來應該是這樣的:

class Sender(models.Model): 
    customer = models.ForeignKey(Customer) 
    # .. and the other fields od a sender 

class Customer(models.Model): 
    customer_id = models.CharField(max_length=244, blank=False, null=False, primary_key=True) 
    # .. and the other fields of a customer 

然後一個查詢集:

# Replace all() with filter(your_params) 
sender_list = Sender.objects.select_related('customer').all() 

your_desired_output = [sender.customer for sender in sender_list] 

selected_related方法告訴Django遵循關係並在同一查詢中獲取相關客戶對象(以避免在遍歷查詢集時爲每個發件人運行單獨的查詢)。在大多數數據庫中,這意味着只有一個選擇與客戶的左連接,所以它會非常有效。

我相信這將是在Django做到這一點的正確方法。如果有一個原因,你不使用主鍵和/或你不能在模型之間建立這樣的關係,那麼你需要嘗試user6731765發送的解決方案或嘗試原始查詢。

+0

感謝您的寶貴意見,發件人和收件人都是客戶對象,並且有一個聯繫表,它具有所有客戶(如聊天應用程序,關係即聊天室)之間的所有關係。我想我可以改變聯繫表來適應這種方法,但它會影響很多代碼,所以現在不能使用這種方法。但是學到了一些新的感謝! – Berk