简体   繁体   English

如何在 Django 中使用日期时间过滤日期时间?

[英]How to filter datetime using datetime in django?

I have a Homework model that I want to filter based on the date(date_view) to show the homework.我有一个作业模型,我想根据日期(date_view)过滤以显示作业。 It looks like this-看起来像这样——

Homework model作业模型

class Homework(models.Model):
    hw_id = models.CharField(unique=True, max_length=50)
    homework = models.TextField()
    subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
    class_id = models.ForeignKey(Classes, on_delete=models.CASCADE)
    date_added = models.DateTimeField(auto_now_add=True)
    date_updated = models.DateTimeField(auto_now=True)
    date_view = models.DateTimeField(default=datetime.now())

But when I try to filter like this-但是当我尝试像这样过滤时-

 hw = Homework.objects.filter(class_id=class_id).filter(date_view__gte='homework__date_added')

I get this error-我收到此错误-

['“homework__date_added” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

I think I am filtering the data in the wrong way.我认为我以错误的方式过滤数据。 But how should I filter the data?但是我应该如何过滤数据?

You can refer to a field with an F object [Django-doc] :您可以使用F对象 [Django-doc]引用字段:

from django.db.models import F

hw = Homework.objects.filter(
    class_id=class_id,
    date_view__gte=F('date_added')
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM