忽略Django模型中的一个字段

时间:2018-12-26 22:23:46

标签: python django

我有一个具有以下四个字段的Django模型:

class File:
    id = models.PrimaryKey()
    name = models.CharField()
    is_active = models.BooleanField()
    data = models.JSONField()

data字段很大,每个条目大约5MB。有没有一种方法可以在我进行ORM查询时隐藏该字段,而不必指定我想每次查看的所有字段?像这样:

File.objects.all() # exclude data field
File.objects.values('id', 'data') # include the data field

2 个答案:

答案 0 :(得分:1)

在某些复杂的数据建模情况下,您的模型可能包含很多字段,其中一些字段可能包含很多数据(例如,文本字段),或者需要昂贵的处理才能将它们转换为Python对象。如果您在某些情况下使用查询集的结果,而在最初获取数据时却不知道是否需要这些特定字段,则可以告诉Django不要从数据库中检索它们。

这是通过将不加载的字段名称传递到I am the father process of the pid 399457 1 2 3 5 7 11 13 17 19 23 I am the father process of the pid 399457 -- pos=25 I am the child process of the pid 399458 -- pos=25 29 31 37 41 43 47 53 59 61 67 I am the child process of the pid 399458 -- pos=54 I am the father process of the pid 399457 -- pos=54 71 73 79 83 89 97 来完成的:

defer()

还要提到,无论何时调用Entry.objects.defer("headline", "body") ,它都会替换要立即加载的字段集。该方法的名称为助记符:仅立即加载这些字段;其余的则递延。

答案 1 :(得分:0)

您可以使用only()来指定所需的字段

File.objects.only('id', 'data')