gpt4 book ai didi

python - 如何通过单独模型中最新对应条目中的文本字段过滤 Django 查询集

转载 作者:行者123 更新时间:2023-11-28 17:28:24 27 4
gpt4 key购买 nike

我有一个模型,我需要几个特定字段的历史数据,所以我将这些字段放入一个具有外键关系的单独模型中。

有点像这样:

class DataThing(models.Model):
# a bunch of fields here...


class DataThingHistory(models.Model):
datathing_id = models.ForeignKey('DataThing', on_delete=models.CASCADE)
text_with_history = models.CharField(max_length=500, null=True, blank=True)
# other similar fields...
timestamp = models.DateTimeField()

现在我正在尝试使用后者最新对应条目中的文本字段来过滤前者模型。

基本上,如果这些不是单独的模型,我会尝试这样做:

search_results = DataThing.objects.filter(text_with_history__icontains=searchterm)

但我还没有想出一个好方法来跨越这种一对多关系并仅使用后一种模型中具有最新时间戳的条目,至少通过使用 Django ORM。

我知道如何使用原始 SQL 执行我想要的查询,但我真的很想尽可能避免使用原始。

最佳答案

此解决方案利用了 distinct(*fields)目前只有 Postgres 支持:

latest_things = DataThingHistory.objects.
order_by('datathing_id_id', '-timestamp').
distinct('datathing_id_id')

lt_with_searchterm = DataThingHistory.objects.
filter(id__in=latest_things, text_with_history__icontains=searchterm)

search_results = DataThing.objects.filter(datathinghistory__in=lt_with_searchterm)

这应该会导致单个数据库查询。为了可读性,我拆分了查询,但您可以将其嵌套到单个语句中。顺便说一句,正如您在这里看到的,foo_id 不是 ForeignKey 字段的好名称。

关于python - 如何通过单独模型中最新对应条目中的文本字段过滤 Django 查询集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36632745/

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