连接两个模型并在Django中连接?

2024-10-06 12:20:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个模型,mpa和Cid-(仅显示相关数据)

class Mpa(models.Model):
    mpa_number = models.CharField(max_length=16)
    legacy_mpa = models.CharField(max_length=100, null=True, blank=True)
    rbc_transit_number = models.CharField(max_length=100, null=True, blank=True)

class Cid(models.Model):
    mpa = models.ForeignKey(Mpa,on_delete=models.CASCADE)
    anchor_cid = models.CharField(max_length=100, null=False, blank=False)
    campaign_name = models.CharField(max_length=100, null=False)
    google_cid = models.CharField(max_length=100, null=True, blank=True)

我使用选择相关的在外键上连接了两个表:

result = Cid.objects.all().select_related('mpa') 

mpa_数与锚cid有一对多关系。 我想在一行中显示所有锚定cid,它对应于一个mpa_编号(模板中有一个表)。 对于连接锚定cid,我使用了Concat如下-

query_set = result.values('mpa_id').annotate(name = Concat('anchor_cid'))

因为.values()返回字典.all()返回模型实例。我想不出一种方法将它们连接在一起并在模板中显示它们。 我已尝试搜索解决方案,但找不到此方案。 也许我正试图用错误的方式来做这件事,有人可以给我指出正确的方向。。 (使用Django 2.1.5和mysql数据库)


Tags: 模型falsetruemodelmodelsnulllengthmax
1条回答
网友
1楼 · 发布于 2024-10-06 12:20:40

models.pyviews.py中执行逻辑可能更容易。例如:

#models.py

class Mpa(models.Model):
    mpa_number = models.CharField(max_length=16)
    legacy_mpa = models.CharField(max_length=100, null=True, blank=True)
    rbc_transit_number = models.CharField(max_length=100, null=True, blank=True)

    def related_cids(self):
        #get a list of values
        anchors = self.cid_set.all().values_list('cid_anchor', flat=True)

        #get set of unique results and convert back to list
        unique_anchors = set(anchors)
        anchor_list = list(unique_anchors)

        #concatenate list values into a long string, separated by
        #single spaces, and return
        return ' '.join(anchor_list)

这里,cid_set是默认的related_name,它允许Mpa实例定位所有相关的Cid实例^{}仅检索实际的cid_anchor值,作为一个简单列表

在模板中,您应该能够执行以下操作:

{{ mpa_object.related_cids }}

相关问题 更多 >