如何从Django中未直接联接的表中检索数据?

时间:2018-11-29 12:05:42

标签: django elasticsearch

我有一个响应表:

class Response(models.Model):
    Question = models.ForeignKey(Question, on_delete=models.CASCADE)
    Topic = models.ForeignKey(Topic, default=13, on_delete=models.CASCADE)
    Response = models.TextField()
    Client = models.ForeignKey(ClientDetail, default=8, on_delete=models.CASCADE)
    Planit_location = models.ForeignKey(Planit_location, default=1, on_delete=models.CASCADE)
    Date_added = models.DateField(default=datetime.date.today)
    Document = models.ForeignKey(Document, default=0, on_delete=models.CASCADE)

    def __str__(self):
        return self.Response

我能够从其他直接与之关联的表中检索数据问题,主题,客户:

views.py

clientList = ClientDetail.objects.all().order_by('Client_name')
topicList = Topic.objects.all().order_by('Topic_name')

现在我要从我的部门表中检索“部门名称”:

class Sector(models.Model):
    Sector_name = models.CharField(max_length=255, default='Sector_name')

    def __str__(self):
        return self.Sector_name

哪些已加入我的客户表:

class ClientDetail(models.Model):
    Sector = models.ForeignKey(Sector, default=8, on_delete=models.CASCADE)
    Client_name = models.CharField(max_length=255, default='Client_name')

    class Meta:
        ordering = ['Client_name']

    def __str__(self):
        return self.Client_name

我无法使用与客户端相同的方法,因为它无法在“响应”表中找到“ Sector_id”字段:

sectorList = Sector.objects.all().order_by('Sector_name')
**THIS DOES NOT WORK**

到目前为止,我只能从“客户”表中检索“ Sector_id”,但是我想要的是“部门名称”

我应该在我的document.py文件中添加一些内容吗?由于我无法使用以前模型中使用的相同方法:

class ResponseDocument20(DocType):
    Client = fields.NestedField(properties={
        'Client_name': fields.TextField(),
        'pk': fields.IntegerField(),
    }, include_in_root=True)
    class Meta:
        model = Response

        fields = [
            'Response',
        ]
        related_models = [ClientDetail]

    def get_instances_from_related(self, related_instance):
        if isinstance(related_instance, ClientDetail):
            return related_instance.response_set.all()

1 个答案:

答案 0 :(得分:0)

使用双下划线到达引用的模型字段,并注释以使别名可读:

clientList = ClientDetail.objects.all() \
.annotate(Sector_name=F('Sector__Sector_name')) \
.order_by('Client_name')

现在,您的查询集具有Sector_nameSector__Sector_name)个值的FK->Sector->Sector_name字段。

F()文档-https://docs.djangoproject.com/en/2.1/ref/models/expressions/#f-expressions