Django根据日期范围进行筛选,如果日期中没有记录,则返回其中的假记录,而不会陷入循环



我有一个非常独特的需求,我没有注意到Django文档中有这样的解决方案。

同样,我不想在数据库查询之后使用任何loop,即使我可以在所有记录上使用loop实现这样的解决方案。

class Example(models.Model):
date = DateField
name = CharField
假设我在表 中有以下记录
[
{date: "2018-01-05", name="jhon doe"},
{date: "2018-01-11", name="jonathan someone"},
{date: "2018-01-21", name="someone developer"},
]

和my query:

Example.objects.filter(date_range=["2018-01-01", "2018-01-31"])

与一般情况一样,当我们查询日期范围时,它返回该范围内的所有记录。

但是我希望当某个日期范围内没有记录时,它应该带有空白记录。

正如我们注意到的,在这个范围内我只有3条记录,所以我期望得到这样的结果

[
{date: "2018-01-01", name="Not Found"},
{date: "2018-01-02", name="Not Found"},
{date: "2018-01-03", name="Not Found"},
{date: "2018-01-04", name="Not Found"},
{date: "2018-01-05", name="jhon doe"},
{date: "2018-01-06", name="Not found"},
'''''to be continued in a range''''
]

有没有人知道在过滤期间准备像上面这样的查询集?我需要它像这样,因为我在前端使用javascript工具,它期望这样的数据。

尽管我可以通过前端编写一个实用程序函数来实现这一点,或者循环所有的查询集并以上述方式准备日期。

除了陷入循环,还有人有解决办法吗?

感谢你建设性的回答

我已经发表了评论,说这是不可能的,当然这取决于我的知识,但我想解释为什么以及如何解决这个问题。

假设您有具有这3条记录的Example模型类。当你做这个查询时;Example.objects.filter(date_range=["2018-01-01", "2018-01-31"])它会像你说的那样在这个范围内获取这些记录但是它无法获取像

这样的记录
{date: "2018-01-01", name="Not Found"},
{date: "2018-01-02", name="Not Found"}...

因为这些对象实际上不存在于数据库中。我认为你必须使用循环来创建那些不在数据库中的记录。可以这样做:

# Initialize your start and end date
date_start = datetime.date(2018, 1, 1)
date_end = datetime.date(2018, 1, 31)
# Get only the dates so that we can find what is not in that range
example_dates = Example.objects.values_list('date', flat=True) 
# Initialize new list that will include records does not exists
not_found_dates = []
# Loop through in date range and if date does not exists 
# Create a dict and add it to your list
for i in range(1, (date_start - date_end).days + 1):
new_date = date_start + datetime.timedelta(days=i)
if new_date not in dates:
not_found_dates.append({'date': new_date, 'name': 'Not Found'}) 
# Get your original queryset
examples = Example.objects.filter(date__range=(date_start, date_end)).values('date', 'name')
# Convert it to a list
examples = list(examples)
# Than extends examples with other list
examples.extend(example_dates)

如果你想使用你的序列化器来转换你的查询集,而不是创建字典作为记录,你应该创建像example=Example.objects.create(**kwargs)和merge 2 queryset这样的对象,以便你的序列化器可以操作它。但是这会在你的数据库中创建新的记录,所以这也可能不是一个好的方法。

最新更新