我有这样的模型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)
你的第二次尝试很接近,但有两个问题:
first
对象,那就是拥有最老的release_date
的对象,而不是最近的gt
代替gte
似乎有点可疑。。。我很惊讶它在只有一个ContentBuild
的时候还能捡到任何东西要在单个db查询中获得它,您有几个选项,具体取决于您的django版本。如果您使用django>;=2.0运行,您应该可以这样做(我现在没有一个项目可以测试它):
如果您使用的是django<;2.0,请尝试以下操作:
也许有一个更聪明的方法,但似乎是可行的。你知道吗
使用
order_by
而不是查询集。试试这个。你知道吗相关问题 更多 >
编程相关推荐