过滤对象少于30天,并将对象的用户排除在特定对象之外

时间:2013-05-18 13:55:04

标签: django

我有两个名为Car and Review的模型。用户可以为汽车写很多评论。 我可以过滤某辆车的所有评论。 我面临的问题是,我只想在不到30天的时间内过滤掉属于特定汽车的所有评论,并排除拥有汽车的用户。

这个问题支持我的问题Getting all items less than a month old,但我无法解决 过滤不到30天内属于特定汽车的所有评论,并排除拥有汽车的用户。

class Car(models.Model):
    user = models.ForeignKey(User)
    name = models.CharField(max_length=11)


class Review(models.Model):
    created = models.DateTimeField(auto_now_add=True)
    user = models.ForeignKey(User)
    review = models.TextField()
    car = models.ForeignKey(Car)

过滤特定车辆的所有评论

Car = Car.objects.get(pk=1)
Review = Review.objects.filter(car=Car)

过滤特定汽车的所有评论,但它会检索30天内我不想要的每辆汽车的所有评论。我想在不到30天的时间内检索特定汽车的评论,并且不包括拥有汽车的用户

Car = Car.objects.get(pk=1)
from datetime import datetime, timedelta
last_month = datetime.today() - timedelta(days=30)
Review = Review.objects.filter(car__in=car,review__gte=month)

我的问题是如何在不到30天的时间内过滤特定汽车的所有评论,而不包括拥有汽车的用户的评论。

谢谢你的帮助

2 个答案:

答案 0 :(得分:2)

首先,您需要在created字段而非review字段上进行过滤,以查找旧条目:

from django.db import Q
from datetime import datetime, timedelta

Car = Car.objects.get(pk=1)
threshold = datetime.now() - timedelta(days=30)

# filtering step by step to give better understanding
reviews = Review.objects.filter(car__id=car.id) # filter by car first
reviews = reviews.filter(created__gte=threshold) # filter by datetime
reviews = reviews.filter(~Q(user__id=car.user.id)) # exclude user reviews who owns the car

# filtering in single step
reviews = Review.objects.filter(
    ~Q(user__id=car.user.id), car__id=car.id, created__gte=threshold)

答案 1 :(得分:1)

如何关注“向后”关系(https://docs.djangoproject.com/en/dev/topics/db/queries/#backwards-related-objects):

from datetime import datetime, timedelta

threshold = datetime.now() - timedelta(days=30)
car = Car.objects.get(pk=1)
reviews = car.review_set.exclude(user=car.user).filter(created__gt=threshold)