2014-10-31 73 views
1

我想找到一個對象模型的下一個實例,但有一定的條件。Django next/prev具有一定條件的模型實例嗎?

Models.py:

class Pin(models.Model): 
    submitter = models.ForeignKey(User) 
    url = models.TextField(blank=True, null=True) 
    price = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=2) 
    published = models.DateTimeField(auto_now_add=True) 

我知道一個實例的pk獲得下一個實例我可以這樣做:

pin = Pin.objects.get(pk=123) 
pin_next = pin.get_next_by_published() 

但我想其中有price不等於空下一針,這樣的一種和條件。下一個實例,但價格不爲空。我可以使用循環繼續查找下一個直到它的價格不爲空。但是有沒有直接的方法?

+0

我認爲get_next_by和get_previous_by只能使用日期。你可能需要編寫自己的方法。 – cezar 2014-10-31 14:34:29

回答

2

你可以通過額外的查找關鍵字參數傳遞給了get_next_by_XXX方法,讓你的上述情況下pin.get_next_by_published(price__isnull=False)應該工作。如果你有更復雜的條件或者想要非基於日期的訂購,你必須編寫自己的方法。

+0

感謝這工作 – Coderaemon 2014-10-31 15:19:02

2

你必須自己編寫查詢,但它是相當瑣碎的:)

注意,因爲published可能不是唯一的,這可能並不總是工作,你期望的那樣。因此,我會建議基於導航的pk

class Pin(models.Model): 
    submitter = models.ForeignKey(User) 
    url = models.TextField(blank=True, null=True) 
    price = models.DecimalField(blank=True, null=True, max_digits=10, decimal_places=2) 
    published = models.DateTimeField(auto_now_add=True) 

    def others(self): 
     return self.objects.exclude(pk=self.pk) 

    def others_with_price(self): 
     return self.others().filter(price__isnull=False) 

    # By primary key: 

    def get_next(self): 
     return self.others_with_price(pk__gt=self.pk).order_by('pk')[0] 

    def get_prev(self): 
     return self.others_with_price(pk__lt=self.pk).order_by('-pk')[0] 

    # By published: 

    def get_next_published(self): 
     return self.others_with_price(published__gte=self.published).order_by('published')[0] 

    def get_prev_published(self): 
     return self.others_with_price(published__lte=self.published).order_by('-published')[0] 
+0

這不會在'發佈'上訂購 - 並且只有在模型的「Meta」中指定了未訂購的訂單時纔會訂購。 – 2014-10-31 14:47:40

+0

@bruno desthuilliers我認爲OP不管出版日期如何,都希望按照價格獲得下一個銷。這就是我對它的理解。 – cezar 2014-10-31 14:50:06

+0

@brunodesthuilliers:固定,謝謝:) – Wolph 2014-10-31 14:53:01

相關問題