简体   繁体   中英

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. 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] :

from django.db.models import F

hw = Homework.objects.filter(
    class_id=class_id,
    
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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