Balraj Gill
Balraj Gill

Reputation: 43

Join two models and concatenate in Django?

I have two models, mpa and Cid - (only displaying relevant data)

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)

I have joined two tables on foreign key, using select_related:

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

mpa_number has one to many relation with anchor_cid. I wanted to display all anchor_cid, that corresponds to an mpa_number, in one row (there is a table in template). For concatenating anchor_cid, I have used Concat like this -

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

Since .values() returns a dictionary and .all() returns a model instance. I can't figure out a way of joining them together and displaying them in template. I have tried searching for a solution but couldn't find this scenario. Maybe I'm trying to do this in wrong way and somebody can point me in right direction.. (using Django 2.1.5 and mysql database)

Upvotes: 0

Views: 729

Answers (1)

gatlanticus
gatlanticus

Reputation: 1226

It's probably easier to do the logic in your models.py or views.py instead. For example:

#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)

Here, cid_set is the default related_name, which allows the Mpa instance to locate all related Cid instances. values_list only retrieves the actual cid_anchor values, as a simple list.

In your template, you should then be able to do:

{{ mpa_object.related_cids }}

Upvotes: 1

Related Questions