【问题标题】:how can i get all the data from my model booking having date less than today i want to show the booking history of customer如何从我的模型预订中获取日期小于今天的所有数据我想显示客户的预订历史记录
【发布时间】:2020-04-21 21:58:59
【问题描述】:

view.py def Profile(request,uid):

book =booking.objects.filter(user=uid)
user =User.objects.get(id=uid)
books = booking.objects.filter(created__lt=datetime.today(),user=uid)

params={'book':book,'user':user,'books':books}
return render(request, 'hotel/userProfile.html',params)

【问题讨论】:

    标签: django date django-views django-filters


    【解决方案1】:

    您的book 变量已在user=uid 上过滤以获取用户的所有预订,请尝试进一步过滤该结果集以限制日期:

    user = User.objects.get(id=uid)
    book = booking.objects.filter(user=user)
    books = book.filter(created__lt=datetime.date.today())
    

    (注意从datetime.today()datetime.date.today() 的变化)

    您还可以使用 Django 的 _set 上下文来获取用户的所有书籍,而不是显式使用 filter(Django 将自动创建一个相关名称作为引用模型的名称,其后缀为 _set你可以用来抓取所有相关的对象——在你的例子中,它会被称为booking_set):

    user = User.objects.get(id=uid)
    books = user.booking_set.all()
    

    顺便说一句,在查询集对象上使用filter 只会返回另一个查询集,因此您可以将它们链接在一起。所以如果你愿意,你可以做这样的事情:

    books = User.objects.get(id=uid).booking_set.all().filter(created__lt=datetime.date.today())

    您应该阅读文档的这一部分,它将解释从数据库中保存和检索记录的所有机制:https://docs.djangoproject.com/en/3.0/topics/db/queries/

    【讨论】:

      【解决方案2】:
              def Profile(request,uid):   
               user =User.objects.get(id=uid) #this displays user information in profile
               books = booking.objects.filter(date__gte=datetime.today(),user=uid) #displays booking date greater than equal to today
               book = booking.objects.filter(date__lt=datetime.today(),user=uid) #displays booking date greater than eqaul to today
               params={'book':book,'user':user,'books':books}
               return render(request, 'hotel/userProfile.html',params)
      

      以上方法也可以!!是的,有点冗长,但对我有用。

      【讨论】:

      • 您在书籍和书籍中复制相同的过滤器...为什么?您应该努力避免程序中出现无用/重复的代码...
      猜你喜欢
      • 1970-01-01
      • 2017-02-03
      • 1970-01-01
      • 2021-07-01
      • 1970-01-01
      • 2018-12-01
      • 1970-01-01
      • 2022-11-24
      • 2021-12-01
      相关资源
      最近更新 更多