Django如何获取符合条件的模型的下一个/上一个实例?
我想找到一个对象模型的下一个实例,但要满足某个条件。
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()
但是我想找到下一个价格不为空的实例,也就是说要加个条件。就是下一个实例,但价格不能是空的。我可以用循环不断查找下一个,直到找到价格不为空的实例。但有没有更直接的方法呢?
2 个回答
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]
2
你可以给 get_next_by_XXX
这些方法传递额外的查找关键字参数。所以在你上面的例子中,pin.get_next_by_published(price__isnull=False)
应该可以正常工作。如果你有更复杂的条件,或者想要按照非日期的顺序排列,你就需要自己写一个方法了。