有没有一个聪明的方式来获取上一个/下一个项目使用Django ORM? [英] Is there a clever way to get the previous/next item using the Django ORM?
问题描述
class Photo(models.Model):
title = models.Char()
image = models.Image()
created = models.DateTimeField(auto_now_add = True)
class Meta:
订购=('-created',)
我有一个任意的Photo对象photo_x。有一种简单的方法可以通过查询中的位置查找上一张和下一张照片吗?另外,如果我在开始/结束时,我想要包装,如果只有1张或2张照片,它不会失败。
你好运!默认情况下,Django会为 DateField
和amp而创建 get_next_by_foo
和 get_previous_by_foo
; DateTimeField
只要他们没有 null = True
。
例如:
>>>从foo.models import请求
>>> r = Request.objects.get(id = 1)
>>> r.get_next_by_created()
<请求:xyz246>
如果你到达一个集合的末尾,它会提出一个 DoesNotExist
异常,您可以轻松地将其用作触发器返回到集合的开头:
> ;>> r2 = r.get_next_by_created()
>>> r2.get_next_by_created()
...
DoesNotExist:请求匹配查询不存在。
进一步阅读:额外的实例方法
Say I have a list of photos ordered by creation date, as follows:
class Photo(models.Model):
title = models.Char()
image = models.Image()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
I have an arbitrary Photo object photo_x. Is there an easy way to find the previous and next photos by position in the queryset? Also, I would like to wrap around if I am at the beginning/end and have it not fail if the are only 1 or 2 photos.
You're in luck! Django creates get_next_by_foo
and get_previous_by_foo
methods by default for DateField
& DateTimeField
as long as they do not have null=True
.
For example:
>>> from foo.models import Request
>>> r = Request.objects.get(id=1)
>>> r.get_next_by_created()
<Request: xyz246>
And if you reach the end of a set it will raise a DoesNotExist
exception, which you could easily use as a trigger to return to the beginning of the set:
>>> r2 = r.get_next_by_created()
>>> r2.get_next_by_created()
...
DoesNotExist: Request matching query does not exist.
Further reading: Extra instance methods
这篇关于有没有一个聪明的方式来获取上一个/下一个项目使用Django ORM?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!