如何提取django_tables2中的相关模型以避免大量查询?

to94eoyn  于 2023-02-14  发布在  Go
关注(0)|答案(1)|浏览(112)

我可能错过了一些简单的东西。我只是缺乏知识或一些如何。我有两个模型,一个是site,另一个是siteField和最重要的一个-siteFieldValue
我的想法是创建一个django表(针对site),使用siteFieldValue中的值作为一行中的数字,针对特定的站点,在特定的标题下。问题是-每个站点可以有50个这样的值。* def render_函数指定的列数 * 站点数等于大量的查询,我希望避免这种情况。
我的问题是--例如,是否有可能预取每个站点(SiteFieldValue.objects.filter(site=record).first()SiteListTable类中的某个位置)的所有值,将它们放入一个数组中,然后通过简单地检查分配给键的值(字段的id),在def render_函数中使用它们。
型号:

class Site(models.Model):
    name = models.CharField(max_length=100)

class SiteField(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=500, null=True, blank=True)

    def __str__(self):
        return self.name

class SiteFieldValue(models.Model):
    site = models.ForeignKey(Site, on_delete=models.CASCADE)
    field = models.ForeignKey(SiteField, on_delete=models.CASCADE)
    value = models.CharField(max_length=500)

表格视图

class SiteListTable(tables.Table):
    name = tables.Column()
    importance = tables.Column(verbose_name='Importance',empty_values=())
    vertical = tables.Column(verbose_name='Vertical',empty_values=())
    #... and many more to come... all values based on siteFieldValue

    def render_importance(self, value, record):
        q = SiteFieldValue.objects.filter(site=record, field=1).first()
        # ^^ I don't want this!! I would want the SiteFieldValue to be prefetched somewhere else for that model and just check the array for field id in here. 
        if (q):
            return q.value
        else:
            return None

    def render_vertical(self, value, record):
        q = SiteFieldValue.objects.filter(site=record, field=2).first()
        # ^^ I don't want this!! I would want the SiteFieldValue to be prefetched somewhere else for that model and just check the array for field id in here. 
        if (q):
            return q.value
        else:
            return None

    class Meta:
        model = Site
        attrs = {
        "class": "table table-striped","thead" : {'class': 'thead-light',}}
        template_name = "django_tables2/bootstrap.html"
        fields = ("name", "importance", "vertical",)
46qrfjad

46qrfjad1#

这也许能让你开始。我把它分成几个步骤,但它们很容易被锁起来。

#Get all the objects you'll need. You can filter as appropriate, say by site__name). 
qs = SiteFieldValue.objects.select_related('site', 'field')
#lets keep things simple and only get the values we want
qs_values = qs.values('site__name','field__name','value')
#qs_values is a queryset. For ease of manipulation, let's make it a list
qs_list = list(qs_values)
#set up a final dict
final_dict = {}
# create the keys (sites) and values so they are all grouped
for site in qs_list:
    #create the sub_dic for the fields if not already created
    if site['site__name'] not in final_dict:
        final_dict[site['site__name']] = {}
        final_dict[site['site__name']][site['name']] = site['site__name']
    final_dict[site['site__name']][site['field__name']] = site['value']
#now lets convert our dict of dicts into a list of dicts
# for use as per table2 docs
data = []
for site in final_dict:
    data.append(final_dict[site])

现在,您有了一个字典列表,例如[{'name':site__name,'col 1 name':value...],可以按照table 2 docs中所示添加它

相关问题