Django queryset过滤器适用于过去的最新情况和未来的所有情况

2024-09-29 07:22:36 发布

您现在位置:Python中文网/ 问答频道 /正文

上下文

我有这样的模型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()

目标

我想返回过去带有release_date的最新ContentBuildDeviceGroupLink对象,以及将来带有release_date的所有ContentBuildDeviceGroupLink对象。你知道吗

我尝试的

我试着这样使用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时,下面的queryset可以正常工作,但当有多个相关的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)

Tags: 对象buildtruedatereleaseuuidmodelsorder
2条回答

你的第二次尝试很接近,但有两个问题:

  1. 既然您要从有序列表中删除first对象,那就是拥有最老的release_date的对象,而不是最近的
  2. gt代替gte似乎有点可疑。。。我很惊讶它在只有一个ContentBuild的时候还能捡到任何东西

要在单个db查询中获得它,您有几个选项,具体取决于您的django版本。如果您使用django>;=2.0运行,您应该可以这样做(我现在没有一个项目可以测试它):

from django.db.models import Max, Q, F

ContentBuildDeviceGroupLink.objects.annotate(
    start_date=Max('release_date', filter=Q(release_date__lt=timezone.now())
).filter(release_date__gte=F('start_date'))

如果您使用的是django<;2.0,请尝试以下操作:

from django.db.models import Subquery, F

recent_dates = ContentBuildDeviceGroupLink.objects.filter(
    release_date__lte=timezone.now()
).order_by('-release_date').values('release_date')

ContentBuildDeviceGroupLink.objects.annotate(
    start_time=Subquery(recent_dates[:1])
).filter(release_date__gte=F('start_time'))

也许有一个更聪明的方法,但似乎是可行的。你知道吗

使用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()

相关问题 更多 >