一个相关模型的过滤器很少有过滤器预取
有一个表order
,它连接到表信号
通过fk
。我从表信号
中循环循环,然后从表order
访问子元素。结果,我得到n+1查询
。尝试做prefetch_recated
,prefetch
,但没有任何帮助。
for profile in Profile.objects.all():
for signal in profile.signals.prefetch_related("orders").all():
filter1 = signal.orders.filter(position_direction=OrderDirectionChoice.ENTER).order_by("exchanged_at")
filter2 = signal.orders.filter(position_direction=OrderDirectionChoice.ENTER)
filter3 = signal.orders.filter(position_direction=OrderDirectionChoice.EXIT)
filter4 = signal.orders.filter(exchanged_at__isnull=False)
print(filter1, filter2, filter3, filter4)
型号
class Profile(models.Model):
...
class Signal(models.Model):
profile = models.ForeignKey(Profile, related_name="signals", ...)
class Order(models.Model):
signal = models.ForeignKey(Signal, related_name="orders", ...)
position_direction = models.CharField(...)
exchanged_at = models.BooleanField(...)
There is a table Order
, which is connected to table Signal
through FK
. I loop through the records from table Signal
and access the child elements from table Order
. As a result, I get N+1 query
. Tried to do prefetch_related
, Prefetch
, but nothing helps.
for profile in Profile.objects.all():
for signal in profile.signals.prefetch_related("orders").all():
filter1 = signal.orders.filter(position_direction=OrderDirectionChoice.ENTER).order_by("exchanged_at")
filter2 = signal.orders.filter(position_direction=OrderDirectionChoice.ENTER)
filter3 = signal.orders.filter(position_direction=OrderDirectionChoice.EXIT)
filter4 = signal.orders.filter(exchanged_at__isnull=False)
print(filter1, filter2, filter3, filter4)
models.py
class Profile(models.Model):
...
class Signal(models.Model):
profile = models.ForeignKey(Profile, related_name="signals", ...)
class Order(models.Model):
signal = models.ForeignKey(Signal, related_name="orders", ...)
position_direction = models.CharField(...)
exchanged_at = models.BooleanField(...)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 对象将其他属性添加到包含自定义预摘情况的返回实例,通过传递
to_attr
参数You can use
Prefetch
objects to add additional attributes to the returned instances that contained custom prefetched querysets by passing theto_attr
argument如果您需要基于配置文件信号的订单列表:
然后,将其他过滤器应用于
profile_orders
varibleprofile_orders = profile_orders.filter.filter(...)
>If you want a list of orders based on the profile Signals:
Then you apply the other filters on the
profile_orders
variableprofile_orders = profile_orders.filter(...)
我认为,在您的算法中存在一个合乎逻辑的错误。
例如:Filter1,Filt2,Felter3是QuerySets,Filter4是对象
但是您仍然可以创建预取:
< noreferrer”> https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.prefetch
I think, in your algorithm exists a logical mistake.
For example: filter1, filter2, filter3 are querysets and filter4 is object
But you still can create Prefetch:
https://docs.djangoproject.com/en/4.0/ref/models/querysets/#django.db.models.Prefetch