2013-12-17 24 views
0

型號:Django的:通過計算標準排序(提前的情況下)

class Customer(models.Model): 
    name = models.CharField(max_length=200) 
    time_categoty = models.IntegerField() 
    importance = models.IntegerField() 

class Interaction(models.Model): 
    i_date = models.DateTimeField() 

class Interaction_customer(models.Model): 
    interaction = models.ForeignKey(Interaction) 
    customer = models.ForeignKey(Customer) 

假設:

c = Customer.objects.get(pk=1) 
x = Interaction.objects.filter(interaction_person__person=c).latest('i_date').i_date 

(即針對特定客戶最新的互動)

需要:名單所有的客戶,通過標準排序: time_category /(datetime.now() - X)* c.importance

請不要給我一個鏈接到djangoproject.com「額外」的,我很仔細地看過,但真的不知道如何實現它在我的情況。 (情況是艱苦的,一個星期沒有人可以幫助,Django的絕地被通緝) 任何有建設性的意見將不勝感激。 謝謝! //埃德

+0

對不起,interaction_person__person = = interaction_customer__customer –

+0

1.最好將計算保存在某個地方,以便於排序(沒有其他明確的方法可以做到這一點,而不會放棄某些效率)2.您的模型看起來像[ManyToMany with'through'](https ://docs.djangoproject.com/en/1.6/topics/db/models/#extra-fields-on-many-to-many-relationships)。我不知道這是否是'額外'的含義,如果不添加任何其他字段,我完全不瞭解您需要什麼Interaction_Customer。更好地直接鏈接它們 – yuvi

+0

我已經刪除了所有與案例無關的字段,但真正的基礎只需要這樣的結構。 // Ed –

回答

0

你在這裏什麼是額外數據的第三模型多對多的關係。通過鏈接它們,你可以獲得額外的api獎勵來直接連接它們(這似乎是必需的)。現在就手頭的問題 - 讓我們先爲客戶創建一種方法來計算該數據:

class Customer(models.Model): 
    name = models.CharField(max_length=200) 
    time_category = models.IntegerField() 
    importance = models.IntegerField() 
    interactions = models.ManyToManyField('Interaction', through='InteractionCustomer') 

    def delta(self): 
     ia = self.interactions.latest('i_date').i_date 
     return self.time_categoty/(datetime.now() - ia) * self.importance 

class Interaction(models.Model): 
    i_date = models.DateTimeField() 

class InteractionCustomer(models.Model): 
    interaction = models.ForeignKey(Interaction) 
    customer = models.ForeignKey(Customer) 

現在我們要按它來排序。你可以使用python:

sorted(Customer.objects.all(), key=lambda x: x.delta()) 

或者,爲了提高效率,你可以將它保存到另一個字段。雖然在這種情況下,你需要不斷更新它。您可以覆蓋保存方法,但節約手頭的客戶對象,這可能並不總是這樣的情況時,將只適用(所以你實現它時,這種方式需要仔細考慮):

class Customer(models.Model): 
    .... 
    delta = models.IntegerField() 

    def save(self, *args, **kwargs): 
     self.delta = self.calc_delta() 
     super(Customer, self).save(*args, **kwargs) 
+0

謝謝爲您的專業和願意提供幫助!該方法很容易實現,它工作正常! –

+0

當然可以!樂於幫忙=] – yuvi

相關問題