gpt4 book ai didi

django - 如何在 lte/gte 比较中包含 "None"?

转载 作者:行者123 更新时间:2023-12-05 01:34:08 25 4
gpt4 key购买 nike

我有这个复杂的过滤机制...

d = copy(request.GET)
d.setdefault('sort_by', 'created')
d.setdefault('sort_dir', 'desc')
form = FilterShipmentForm(d)
filter = {
'status': ShipmentStatuses.ACTIVE
}
exclude = {}
if not request.user.is_staff:
filter['user__is_staff'] = False

if request.user.is_authenticated():
exclude['user__blocked_by__blocked'] = request.user

if form.is_valid():
d = form.cleaned_data
if d.get('pickup_city'): filter['pickup_address__city__icontains'] = d['pickup_city']
if d.get('dropoff_city'): filter['dropoff_address__city__icontains'] = d['dropoff_city']
if d.get('pickup_province'): filter['pickup_address__province__exact'] = d['pickup_province']
if d.get('dropoff_province'): filter['dropoff_address__province__exact'] = d['dropoff_province']
if d.get('pickup_country'): filter['pickup_address__country__exact'] = d['pickup_country']
if d.get('dropoff_country'): filter['dropoff_address__country__exact'] = d['dropoff_country']
if d.get('min_price'): filter['target_price__gte'] = d['min_price']
if d.get('max_price'): filter['target_price__lte'] = d['max_price']
if d.get('min_distance'): filter['distance__gte'] = d['min_distance'] * 1000
if d.get('max_distance'): filter['distance__lte'] = d['max_distance'] * 1000
if d.get('available_on'): # <--- RELEVANT BIT HERE ---
filter['pickup_earliest__lte'] = d['available_on'] # basically I want "lte OR none"
filter['pickup_latest__gte'] = d['available_on']
if d.get('shipper'): filter['user__username__iexact'] = d['shipper']

order = ife(d['sort_dir'] == 'desc', '-') + d['sort_by']

shipments = Shipment.objects.filter(**filter).exclude(**exclude).order_by(order) \
.annotate(num_bids=Count('bids'), min_bid=Min('bids__amount'), max_bid=Max('bids__amount'))

现在我的客户告诉我,他希望可以选择“灵活”的取件/还件日期。因此,我更新了数据库以允许为此目的将日期设置为 NULL,但现在“可供取货日期”过滤器将无法按预期工作。它应该包括 NULL/None 日期。有解决此问题的简单方法吗?

最佳答案

翻转逻辑并使用exclude()。您真正想要做的是排除任何指定不适合日期的数据。如果 pickup_latestpickup_earliestNULL,则它不应与排除查询匹配并且不会被删除。例如

exclude['pickup_latest__lt'] = d['available_on']
exclude['pickup_earliest__gt'] = d['available_on']

关于django - 如何在 lte/gte 比较中包含 "None"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3877581/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com