我的 Django 应用程序中有一个基本的 Item 模型:
class Item(models.Model):
name = models.CharField(max_length=200)
brand = models.ForeignKey(User, related_name='items')
price = models.CharField(max_length=10)
upload_date = models.DateTimeField(auto_now=False, auto_now_add=True)
对于给定的项目,我正在尝试获取数据库中的下一个和上一个项目。
我知道我可以使用 Django 的内置 Model.get_next_by_FOO(**kwargs)
来做到这一点,它与 upload_date
字段配合得很好,但我需要在给定特定 OR 参数的情况下获取上一个和下一个项目(例如,具有特定品牌或低于特定价格的项目)。
我可以使用这样的查询获取上一个项目:
previous_item = Item.objects.filter(id__lt=item.id).filter(Q(brand__in=brands)|Q(price__lt=100))[:1]
我的问题是下一项。对下一个项目运行相同的查询会导致总体上符合条件的最新项目,而不是数据库中当前项目之后的项目。我知道这是因为 Django 查询数据库的方式,但不知道如何绕过它来获取紧跟在当前项目之后也符合条件的项目。
在给定多个 OR 参数的情况下,是否有一种快速、简单的方法来获取特定项目的下一个项目?
谢谢!
最佳答案
我没有对此进行任何测试,所以可能只是胡说八道,但这也许是一个起点?
编辑:哦,是的,你很清楚“或”的问题,但我还是错过了。再试一次。基本思想是将您的查询转换为列表并合并列表。但是现在想想——我认为你可以自己创建实际的查询集——在这种情况下它可能有用吗?您可以在函数中完成 OR 的常见繁重工作,然后传回一个可以由 View 进一步操作的查询集。
def get_next(item, brand=None, max_price=None)
"""Returns the next item to the one provided"""
# apply limits to brand/price as specified
if brand is not None:
brand_candy = Item.objects.filter(brand=brand)\
.values_list('id','update_date')
if max_price is not None
price_candy = Item.objects.filter(price__lt=max_price)\
.values_list('id','update_date')
# arrange all candidates into a joined list
# TODO: finish this to merge the lists and sort by update_date
ids = brand_candy.join(price_candy)
# find the location of the current item in the list
# TODO: handle not being there
idx = ids.index(item.id)
# TODO: handle edges of the list
next_idx = idx + 1
# pluck out the next item
return Item.objects.get(id=ids[next_idx])
关于mysql - Django:在给定多个 OR 参数的情况下获取特定项目的下一个和上一个项目 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7356175/