如何通过ForeignKey prefetch_related建立连接?

时间:2021-05-03 20:15:22

I need to optimize my table. In template in each row displays information about the graphic and creates each time a query. If I have a lot of lines, it takes a very long time.

我需要优化我的桌子。在每行的模板中显示有关图形的信息,并在每次查询时创建。如果我有很多行,那需要很长时间。

My model:

我的模特:

class Graphic(models.Model):
    text = CharField(...)
    comment = CharField(...)
    profile = ForeignKey(Profile)


class CardiogramData(models.Model):
    date = models.DateTimeField(...)
    cardiogram = models.ForeignKey('common.Graphic', related_name='data_set')

If the connection was from the class of graphic, then everything would be easy.

如果连接来自图形类,那么一切都会很简单。

In view:

在视图中:

...
    queryset = Graphic.objects.prefetch_related('profile', 'data_set')

'data_set' does not work, but 'profile' works as needed.

'data_set'不起作用,但'profile'可以根据需要运行。

1 个解决方案

#1


1  

try:

尝试:

queryset = Graphic.objects.select_related('profile').prefetch_related('data_set')

#1


1  

try:

尝试:

queryset = Graphic.objects.select_related('profile').prefetch_related('data_set')