Django的ORM支持通过.using()函数从特定数据库(在项目中定义多个数据库)中查询基于过滤器的操作.
例如 MyModel.objects.filter(name='Bob').using('my_non_default_database')
通过类MyModel()或快捷方式(如get_or_create())创建新记录时,您将如何进行等效操作?
a = M.objects.filter(f__in=[None, 1])
a.query.__str__()
u'SELECT * FROM "app_m" WHERE "app_m"."f" IN (None, 1)'
Run Code Online (Sandbox Code Playgroud)
你不觉得那会IN (NULL, 1)吗?
喜欢:
a = M.objects.filter(f=None)
a.query.__str__()
u'SELECT * FROM "app_m" WHERE "app_m"."f" IS NULL'
Run Code Online (Sandbox Code Playgroud)
这是一个默认的SQL行为,django bug还是我错过了什么f__in=?
先感谢您!
我有一张桌子student。它具有以下属性
name,
age,
school_passout_date,
college_start_date
我需要一份报告,以了解avg number of days在通过学校和开始大学学习之间,学生可以获得什么自由。
目前,我正在为每个学生寻找天数并获取其平均值的价值范围感到恼怒。
当记录集变大时,效率极低。
Django ORM中有什么功能可以给我两个日期之间的总计天数?
我正在寻找这样的东西。
Students.objects.filter(school_passed=True, started_college=True).annotate(total_days_between=Count('school_passout_date', 'college_start_date'), Avg_days=Avg('school_passout_date', 'college_start_date'))
Run Code Online (Sandbox Code Playgroud)
最好,
我有以下申请:
from django.db import models
class Worker(models.Model):
name = models.CharField(max_length=60)
def __str__(self):
return self.name
class Job(models.Model):
worker = models.ForeignKey(Worker)
is_completed = models.BooleanField()
Run Code Online (Sandbox Code Playgroud)
我想用已完成作业的数量来注释Workers查询.
我将尝试使用以下脚本:
from myapp.models import Worker, Job
from django.db.models import Count
w = Worker.objects.create(name='Worker1')
Job.objects.create(worker=w, is_completed=False)
Job.objects.create(worker=w, is_completed=False)
Job.objects.create(worker=w, is_completed=True)
Job.objects.create(worker=w, is_completed=True)
workers = Worker.objects.all().annotate(num_jobs=Count('job'))
workers[0].num_jobs
# >>> 4
workers = Worker.objects.all().exclude(job__is_completed=False).annotate(num_jobs=Count('job'))
# >>> []
Run Code Online (Sandbox Code Playgroud)
最后一个查询的结果为空.如何从反向关系中排除元素?
Django 1.8,python 2.7
UPD.我希望查询集中的所有工作人员,即使是那些没有工作的人
有什么区别
queryset.filter(Q(foo='bar') | Q(foo='baz'))
Run Code Online (Sandbox Code Playgroud)
和
queryset.filter(foo__in=['bar', 'baz'])
Run Code Online (Sandbox Code Playgroud)
我发现有时他们会产生不同的结果,我无法弄清楚为什么.
我对这些查询得到了不同的结果:
In [8]: Profile.objects.filter(image="").count()
Out[8]: 7173
In [9]: Profile.objects.filter(image=None).count()
Out[9]: 25946
In [10]: Profile.objects.filter(image__in=["", None]).count()
Out[10]: 7173
In [11]: Profile.objects.filter(Q(image="") | Q(image=None)).count()
Out[11]: 33119
Run Code Online (Sandbox Code Playgroud)
我正在使用PostgreSQL作为我的数据库引擎.
我有一个问题模型:
class Question(models.Model):
....
Run Code Online (Sandbox Code Playgroud)
和一个与之相关的答案模型:
class Answer(models.Model):
user = models.ForeignKey(User)
question = models.ForeignKey(Question, on_delete=models.CASCADE)
Run Code Online (Sandbox Code Playgroud)
我想过滤掉所有没有答案的问题.我怎么能在视图中这样做?
假设我有一个具有以下模型定义的事务列表:
class Transaction(models.Model):
amount = models.FloatField()
client = models.ForeignKey(Client)
date = models.DateField()
description = models.CharField()
invoice = models.ForeignKey(Invoice, null=True)
Run Code Online (Sandbox Code Playgroud)
现在我想在月底为每个客户创建发票.发票模型如下所示:
class Invoice(models.Model):
client = models.ForeignKey(Client)
invoice_date = models.DateField()
invoice_number = models.CharField(unique=True)
def amount_due(self):
return self.transaction_set.aggregate(Sum('amount'))
def create_invoices(invoice_date):
for client in Client.objects.all():
transactions = Transaction.objects.filter(client=client)
if transactions.exists():
invoice = Invoice(client=client, number=get_invoice_number(), date=invoice_date)
invoice.save()
transactions.update(invoice=invoice)
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过批量创建在1个查询中创建批量创建的所有发票,但我仍然需要单独在交易模型中设置发票字段.
在创建所有发票后,是否可以使用单个查询设置所有交易模型的发票字段?最好在使用ORM时,但如果需要,很乐意使用原始SQL.
我知道我也可以在交易清单上使用逐个客户来获取每个客户的总数,但随后各个条目都没有链接到发票.
我见过 Django 2.0 由查询FilteredRelation集中的对象组成。新引入的用法是FilteredRelation什么?
我观察了Django 2.0 文档,但我无法理解这个FilteredRelation对象背后的想法。
我查看了以下代码。但我没有得到它。
>>> from django.db.models import FilteredRelation, Q
>>> Restaurant.objects.annotate(
... pizzas_vegetarian=FilteredRelation(
... 'pizzas', condition=Q(pizzas__vegetarian=True),
... ),
... ).filter(pizzas_vegetarian__name__icontains='mozzarella')
Run Code Online (Sandbox Code Playgroud)
现在显示我的问题是
FilteredRelation在你的QuerySet?
我有一个存储在 Postgres 数据库中的 Django 模型,它由不规则间隔的计数值组成:
WidgetCount
- Time
- Count
Run Code Online (Sandbox Code Playgroud)
我正在尝试使用带有 Lag 的窗口函数来为我提供前一行的值作为注释。我的问题是当我尝试将它与一些不同的日期截断结合起来时,窗口函数使用源行而不是明显分组的行。
例如,如果我有以下几行:
time count
2020-01-20 05:00 15
2020-01-20 06:00 20
2020-01-20 09:00 30
2020-01-21 06:00 35
2020-01-21 07:00 40
2020-01-22 04:00 50
2020-01-22 06:00 54
2020-01-22 09:00 58
Run Code Online (Sandbox Code Playgroud)
我想返回一个显示每天第一次阅读的查询集,我可以使用:
from django.db.models.functions import Trunc
WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day"))
Run Code Online (Sandbox Code Playgroud)
这给了我:
date count
01/01/20 15
01/01/21 35
01/01/22 50
Run Code Online (Sandbox Code Playgroud)
我想添加一个注释,它给我昨天的值(这样我就可以显示每天的变化)。
date count yesterday_count
01/01/20 15
01/01/21 35 15
01/01/22 50 35
Run Code Online (Sandbox Code Playgroud)
如果我做:
from django.db.models.functions import Trunc, Lag
from django.db.models import Window
WidgetCount.objects.distinct("date").annotate(date=Trunc("time", "day"), …Run Code Online (Sandbox Code Playgroud) 在Django的2.2文件,我使用的,给出了下面的例子中使用select_for_update:
from django.db import transaction
entries = Entry.objects.select_for_update().filter(author=request.user)
with transaction.atomic():
for entry in entries:
...
Run Code Online (Sandbox Code Playgroud)
Using this approach, one would presumably mutate the model instances assigned to entry and call save on these.
There are cases where I'd prefer the alternative approach below, but I'm unsure whether it would work (or even make sense) with select_for_update.
with transaction.atomic():
Entry.objects.select_for_update().filter(author=request.user).update(foo="bar", wobble="wibble")
Run Code Online (Sandbox Code Playgroud)
The documentation states that the lock is created when the queryset is evaluated, so …