Django:如果使用了select_related(),则排除字段

时间:2018-10-04 13:15:17

标签: django django-select-related

我有一个像这样的Job and Blob模型:

class Job(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True)
    start_time = models.DateTimeField()
    input = models.ForeignKey('Blob')


class DeferContentManager(models.Manager):
    use_for_related_fields = True

    def get_queryset(self, *args, **kwargs):
        return super(DeferContentManager, self).get_queryset(*args, **kwargs).defer('content')

class Blob(models.Model):
    content = models.BinaryField()
    name = models.CharField(max_length=10000, default='')


    objects = DeferContentManager()

不幸的是,有一个执行此操作的Django ORM查询:

Job.objects.filter(....).select_related()

这将加载作业的BinaryFields,我们将收到MemoryError。

如果我像上面那样执行select_related()查询,是否可以排除BinaryField content

PS:我知道我可以更改查询并使用select_related('non_binary_field'),但是这里需要一个通用的解决方案。我没有访问此行的代码:Job.objects.filter(....).select_related()

1 个答案:

答案 0 :(得分:1)

您应在base_manager_name中定义Meta

use_for_related_fields = Truedeprecated with 1.10removed in 2.0

请参阅:https://docs.djangoproject.com/en/1.11/ref/models/options/#base-manager-name