Skip to main content
 首页 » 编程设计

python之Django 查询集过滤器,用于过去和将来的所有查询

2024年08月13日43傻小

上下文

我有模型 ContentBuild & ContentBuildDeviceGroupLink像这样:

# models.py 
 
class ContentBuild(models.Model): 
    content_build_uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) 
 
 
class ContentBuildDeviceGroupLink(models.Model): 
    uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, db_index=True) 
    content_build_uuid = models.ForeignKey(ContentBuild, on_delete=models.CASCADE, related_name='content_build_deploy') 
    group_uuid = models.ForeignKey(DeviceGroup, on_delete=models.CASCADE) 
    preload_date = UnixDateTimeField() 
    release_date = UnixDateTimeField() 

目标

我想返回最近的 ContentBuildDeviceGroupLink带有 release_date 的对象过去,连同所有ContentBuildDeviceGroupLink带有 release_date 的对象 future 。

我尝试了什么

我尝试使用 Q object像这样:

in_future = Q(release_date__gte=timezone.now()) 
recent_past = Q(release_date__lt=timezone.now()).order_by('-release_date')[0] 
 
ContentBuildDeviceGroupLink.objects 
.filter(in_future & recent_past) 

这不起作用并抛出错误:

'datetime.datetime' object has no attribute 'order_by' 

如何使用 release_date 过滤对象在最近的过去和所有带有 release_date 的对象将来呢?

编辑

我改变了我的方法,所以我首先获取最近的对象,然后过滤所有大于或等于该日期的对象。但是,当只有 1 个 ContentBuild 时,下面的查询集工作正常但当有超过 1 个相关时返回所有旧对象 ContentBuild .

recent_past = ContentBuildDeviceGroupLink.objects 
    .filter(release_date__lte=timezone.now()).order_by('release_date').first() 
 
ContentBuildDeviceGroupLink.objects.filter(release_date__gt=recent_past.release_date) 

请您参考如下方法:

您使用 order_by 而不是查询集。试试这个。

in_future = Q(release_date__gte=timezone.now()) 
recent_past = Q(release_date__lt=timezone.now()) 
 
ContentBuildDeviceGroupLink.objects.filter( 
    in_future & recent_past 
).order_by('-release_date').first()