2016-11-20 52 views
-1

比方說,我有這樣的模式:如何在Django或SQL中查詢非唯一值?

class Contact(BaseModel): 
    order = models.ForeignKey(Order, related_name='contacts', blank=True, null=True) 
    type = models.CharField(max_length=15, choices=TYPES, blank=True)) 

我想找到所有的訂單,其中ordertype不是唯一的一起。

例如,有order A並有相關聯繫人:

Contact(order=orderA, type='broker') 
Contact(order=orderA, type='broker') 
Contact(order=orderA, type='delivery') 

我想找到這個orderA因爲這種秩序和type='broker'在一起並不是唯一在Contact模型。

再有就是orderB和這些相關的聯繫人:

Contact(order=orderB, type='broker') 
Contact(order=orderB, type='delivery') 

我不想要這個orderB,因爲它和現場typeContact模式是獨一無二的。

我嘗試使用Django的annonate()但未能涉及這兩個領域。

Django查詢可以做到這一點嗎?

如果不是,我將不勝感激。

非常感謝。

回答

1

你可以寫幾個方法來解決這個問題。我可能已經爲你寫了這些方法,但無論是何種解釋。 def equal_to需要自己和其他聯繫人,如果該聯繫人是相同的訂單並且其他類型爲false,則返回true。 def all_not_unique返回所有不是唯一的聯繫人對象的列表,沒有重複。並應該像not_unique = Contact.all_not_unique()那樣。

def equal_to(self, other): 
    assert(self.id != other.id) 
    if self.order.id == other.order.id: 
     if self.type == other.type: 
      return True 
    return false 

@classmethod 
def all_not_unique(cls): 
    query_set = cls.objects.all() 
    not_unique_query_set = [] 
    for contact_one in query_set: 
     found = False 
     for contact_two in query_set: 
      if not found: 
       if contact_one.id != contact_two.id: 
        if contact_one.equal_to(contact_two): 
         not_unique_query_set.append(contact_one) 
         found = True 
3

你可以使用像一個SQL查詢:

select distinct order_id 
from (
    select order_id, type 
    from Contact 
    group by order_id, type 
    having count(*) > 1); 

「順序」一欄顯示爲「ORDER_ID」,因爲這是方式Django的名字列。

+0

'order'應該是'order_id',你應該添加別名的子查詢,但除此之外,這應該工作。 –

+0

@rd_nielsen謝謝。如果您通過Назар建議更正,我會接受它。謝謝你們兩位。 –

1

這應該做的伎倆

qs = (Contact.objects.values('order','type') 
     .annotate(cnt=models.Count('pk')) 
     .filter(cnt__gt=1))