Django - 通过id加入两个查询集?

时间:2018-01-10 16:47:02

标签: python django

我尝试在发送到视图之前将两个表连接在一起,在视图中使用_set会导致100次查询效率非常低。

示例结构sites.models.py

class SiteData(models.Model):
    location = models.CharField(max_length=50)
    site_type = models.ForeignKey(SiteTypes, verbose_name="Site Type", \
                on_delete=models.PROTECT)
    bgp_as = models.CharField(max_length=6, verbose_name="BGP AS Number")
    opening_date = models.DateField(verbose_name="Site opening date")
    last_hw_refresh_date = models.DateField(verbose_name="Date of latest hardware refresh", \
                           blank=True, null=True)
    is_live = models.BooleanField(default=False, verbose_name="Is this a live site?")

示例结构config.models.py

class SiteSubnets(models.Model):
    site_data = models.ForeignKey(SiteData, verbose_name="Location", \
                on_delete=models.PROTECT, blank=True, null=True)               
    subnet = models.GenericIPAddressField(protocol='IPv4', \
             verbose_name="Subnet", blank=True, null=True)
    subnet_type = models.ForeignKey(SubnetTypes, verbose_name="Subnet Type") 
    vlan_id = models.IntegerField(verbose_name="Vlan ID", blank=True, null=True)
    peer_desc = models.IntegerField(verbose_name="Peer description", blank=True, null=True)
    site_ip = models.BooleanField(default=False, verbose_name="Is this a site supernet IP?")
    class Meta:
        verbose_name = "Site Subnets"
        verbose_name_plural = "Site Subnets"

查询:

site_subnets = SiteSubnets.objects.only('subnet').filter(site_ip=True)
site_data = SiteData.objects.only('location','is_live','bgp_as','postcode','opening_date','live_link_type')

期望的结果示例:

Location   | Subnet     | BGP AS
---------------------------------
London     | 10.10.10.0 | 65001
Manchester | 10.10.20.0 | 65002
...

我不能在没有SitesSubnet表作为主表的情况下执行select_related,就像我在站点数据上做的那样,我得到了

django.core.exceptions.FieldError: Invalid field name(s) given in select_related: 'site_subnets'. Choices are: site_type

如果我使用SiteSubnet作为主表,如果站点没有SiteSubnet.site_up,我将无法获得站点信息。显示

有没有人知道这方面会显示所有数据而不是运行n + 1个查询?

编辑:

预取也会因以下错误而失败:

AttributeError: Cannot find 'site_subnets_set' on SiteData object, 'site_subnets_set' is an invalid parameter to prefetch_related()

我会将数据发送到模板中以便循环访问,即

<table>
  <tr>
    <td>Location</td>
    <td>Subnet</td>
    <td>BGP AS</td>  
  <tr>
{%for site in sitedata %}
  <tr>
    <td>{{ site.location }}</td>
    <td>{{ site.subnet }}</td>
    <td>{{ site.bg_as }}</td>  
  <tr>
{% endfor %}

由于

1 个答案:

答案 0 :(得分:1)

您可以使用model <- felm(y ~ x1 + x2 + xn | factor(xfixedeffects) , data = df) 为sitedata查询集预取网站子网。

prefetch_related