如何使用未直接联接的postgresql从Django的两个表中检索数据?

时间:2018-11-22 11:07:09

标签: python django-models

我有一个“响应,客户和部门”表。响应和客户已加入,客户和部门已加入。

models.py:

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

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

我能够检索客户端数据,因为它们直接链接到响应表。

我需要在我的document.py中添加什么?

documents.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()

我该如何为链接到某个客户的响应检索部门名称?

views.py:

clientList = ClientDetail.objects.all().order_by('Client_name')
sectorList = ????

0 个答案:

没有答案