如何从对象中延迟多对多字段?

2024-05-08 01:03:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从模型中延迟一个字段,但是.defer()似乎不起作用。你知道吗

我正在用python2.7运行Django 1.9。你知道吗

(示例代码,简化)


他说型号.py你知道吗


class MyModelA(models.Model):
    title = models.CharField(max_lenght=50)
    file = models.FileField(upload_to='test/')


class MyModelB(models.Model):
    title = models.CharField(max_lenght=50)
    defer_this = models.ManyToManyField(MyModelA, blank=True)

他说视图.py你知道吗

query =  MyModelB.objects.defer('defer_this')

for i in query:
    print i.title, i.defer_this.all()


它把这些物体打印出来。你知道吗

谁能解释一下它是怎么工作的/为什么会这样?你知道吗


Tags: djangopy模型modeltitlemodelsthisquery
1条回答
网友
1楼 · 发布于 2024-05-08 01:03:32

根据文件

If you are using the results of a queryset in some situation where you don’t know if you need those particular fields when you initially fetch the data, you can tell Django not to retrieve them from the database.

This is done by passing the names of the fields to not load to defer()

A queryset that has deferred fields will still return model instances. Each deferred field will be retrieved from the database if you access that field (one at a time, not all the deferred fields at once)

这意味着defer不会阻止您访问传递给defer的属性。它不会从数据库中获取它。当您尝试访问属性时。然后它将从数据库中获取它。你知道吗

对于M2M字段,它们默认(有点)延迟。当您查询一个包含M2M字段的模型时,django不会进行连接并从相关表中获取数据。您必须显式地告诉django使用prefetch_relatedselected_related进行连接并获取相关数据。你知道吗

相关问题 更多 >