有人能帮我吗?我正在尝试使用一个带有Q的django过滤器。这是我的函数
def get_first_time_customer_ids(year: int, month: int) -> QuerySet:
return Customer.objects.filter(
Q(bookings__status=Booking.STATUS.completed, bookings__pickup_time__year=year, bookings__pickup_time__month=month) &
~Q(bookings__status=Booking.STATUS.completed, bookings__pickup_time__lt=date(year, month, 1))
).distinct().values_list('id', flat=True)
我想实现的是产生所有的客户ID,有第一次预订任何给定的年份和月份。但它失败了我的测试用例。我的测试用例:
def test_get_first_time_customer_ids(self) -> None:
customer_1 = Customer.objects.create(name="Customer 1")
customer_2 = Customer.objects.create(name="Customer 2")
Booking.objects.bulk_create([
Booking(number="A", customer=customer_1, price=100_000, status=Booking.STATUS.completed,
pickup_time=dt(2023, 2, 4, 12), route_id=1, vehicle_category_id=1),
Booking(number="B", customer=customer_1, price=100_000, status=Booking.STATUS.completed,
pickup_time=dt(2023, 1, 5, 12), route_id=1, vehicle_category_id=1),
Booking(number="E", customer=customer_2, price=100_000, status=Booking.STATUS.completed,
pickup_time=dt(2023, 2, 10, 12), route_id=1, vehicle_category_id=1)
])
ids = get_first_time_customer_ids(2023, 2)
self.assertTrue(customer_2.id in ids)
self.assertFalse(customer_1.id in ids)
最后一行出错。查询中包含customer_1的客户ID,它不应该包含。如有任何帮助,我们将不胜感激
1条答案
按热度按时间cwtwac6a1#
我为两个查询集(
qs1
,qs2
)添加了不同的操作,但在原始代码中,不同的操作只在最后。